Search code examples
vue.js.htaccesssingle-page-applicationvue-cli

How to redirect to https index.html with .htacess


I have a vue-laravel spa. For the vue app to work properly with the history mode, I need to make sure that it redirects to index.html. I am following what the vue cli documentation says for that and use this piece of code in the .htaccess file

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

At the same time I also need to make sure that all http request are redirected to https for which my hostgator hosting provided me with this piece of code.

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com$
RewriteRule ^/?$ "https\:\/\/subdomain\.domain\.com\/" [R=301,L]

The problem is that these 2 pieces of code don't seem to work together. Each of them work when the other is commented out though.


Solution

  • Order is important. The canonical (HTTP to HTTPS) redirect needs to go before the rewrites to index.html.

    RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com$
    RewriteRule ^/?$ "https\:\/\/subdomain\.domain\.com\/" [R=301,L]
    

    However, this rule as written redirects to itself and would result in a redirect-loop! (This isn't part of the HTTP to HTTPS redirect.)

    You do not need the <IfModule> wrapper and you do not need to repeat the RewriteEngine directive.

    In other words:

    RewriteEngine On
    
    # Redirect HTTP to HTTPS
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
    
    # Front-Controller
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
    

    You're not actually using the RewriteBase directive, so I removed it.