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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.