2

I have an Angular 5 application and I need to redirect all the traffic to Https when it's not already the case. I only have access to .htaccess to do that.

At first, i had that configuration :

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

Works fine to avoid 404 and let Angular handle the routing, but when i try to add https, it broke everything.

I've tried multiple things, first i tried to add :

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

But I got too many redirections and can't load the page

Then I tried to replace my conf with :

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

All the URI are handled but they always redirect to "/" in Angular, so I can't use Url to navigate (for example I have a /admin section that can be accessed only by URL )

I'm not used to apache, I usually work with nginx, does somebody have an idea on how to fix my issue?

Thanks

mel-mouk
  • 98
  • 9

2 Answers2

1

In case somebody has the same problem, i managed to make it work with this .htaccess :

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{ENV:HTTPS} !on
  RewriteRule (.*) https://%{HTTP_HOST}/$1 [R,L]

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

I guess the error in my first try was the condition for the https test

mel-mouk
  • 98
  • 9
0

Thanks mel-mouk. In my case my dist files are directly in public_html so I don't need to rewrite base, and I tried your solution without it but it didn't work, eventually I think I have a good idea why it failed (through trial and error/experimenting) and it's that between each line my server apparently needs an empty line, something like:

<IfModule mod_rewrite.c>

RewriteEngine On

instead of:

<IfModule mod_rewrite.c>
RewriteEngine On

It is super weird but I understand why it happens. Regardless I thought I'd let anyone else know to check for this if absolutely nothing is working for you.

msamprz
  • 573
  • 2
  • 7
  • 15