Search code examples
apache.htaccessmod-rewrite

How can I redirect all www traffic to non www url in vue project


I have the following code in my htaccess file which is supposed to redirect all www requests to the non www version of index.html, but its not working and I'm not sure why. Can anyone help?

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^www\.
  RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Solution

  • Have it like this:

      RewriteEngine On
      RewriteBase /
    
      RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
      RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
    
      RewriteRule ^index\.html$ - [L,NC]
    
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . index.html [L]
    

    Here we are capturing value after www. in a capture group and then using that as %1 in target URL.

    Make sure to clear your browser cache or use a new browser before you test this change.