Asked  7 Months ago    Answers:  5   Viewed   23 times

I have a website that doesn't seem to redirect from non-www to www.

My Apache configuration is as follows:

RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^ [nc]
RewriteRule ^(.*)$$1 [r=301,nc] 

What am I missing?



Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:

<VirtualHost *:80>
    Redirect permanent /

<VirtualHost *:80>
    # real server configuration

And then you'll have another <VirtualHost> section with ServerName for your real server configuration. Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).

Tuesday, June 1, 2021
answered 7 Months ago

Add the following rule as the first rule:

RewriteCond %{HTTP_HOST} !^(www).
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Wednesday, March 31, 2021
answered 9 Months ago

You should have a look at the URL Rewriting Guide from the apache documentation.

The following is untested, but it should to the trick:

RewriteCond %{HTTP_HOST} ^([^.]+)$
RewriteRule ^/(.*)$ $1 [L,R] 

This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.

Sunday, June 13, 2021
answered 6 Months ago

So i found the answer from another question.

Node.js: 301 redirect non-www without express

Sorry for not searching before

app.get ('/*', function (req, res, next){
  if (!^www./)){
      res.writeHead (301, {'Location': ''});
     return next();
Friday, August 27, 2021
answered 3 Months ago

Try this:

RewriteCond %{REQUEST_URI} !.(gif|jpg|css|js|ico|png)$ [NC]
RewriteCond %{REQUEST_URI} !^/(sitemap.html|includes(/.*|))$ [NC]
RewriteRule ^ /sitemap.html [R=301,L]

Sure both RewriteCond lines can be combined into 1 but I would suggest keeping it 2 separate as this is easier to read and easy to maintain in case you want to add new extensions or new directories for exclusion in future.

Friday, November 19, 2021
Nitin Vijay
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :