2
votes

Would like to do the following on my website using .htaccess rewrite mod:

  • redirect users without https://* to https://*
  • redirect users with www.example.com to example.com
  • rewrite example.com/index.htm to example.com/home
  • redirect every URI to index.htm exept of /home, /background.jpg, /icon.png and /fonts/segoeui.ttf

This is the code I already have:

RewriteEngine On
RewriteBase /

RewriteRule ^\.htaccess$ - [F]

# --- Part that looks stupid but is working ---
RewriteCond %{SERVER_PORT} !^443 
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# --- Part that is not really working ---
RewriteCond %{REQUEST_URI} !^/(index\.htm)?$ [NC]
RewriteRule ^.*$ /index.htm [L,R=301]

So, is there a better way to combine the https and the www thing? It is more a copy and paste solution than good code. I have not much knowledge with this.

The redirection to index.htm is working, but how can I prevent /background.jpg, /icon.png and /fonts/segoeui.ttf from being redirected too? And what about rewriting the whole thing to /home?


Thanks for your help!

1

1 Answers

3
votes

You can combine first two conditions in only one

# Force https and non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Then, rewrite example.com/index.htm to example.com/home

# Redirect /index.htm to /home and avoids infinite redirect loop
RewriteCond %{THE_REQUEST} \s/index\.htm\s [NC]
RewriteRule ^ /home [R=301,L]

# Rewrite (internally) /home to /index.htm
RewriteRule ^home$ /index.htm [L]

Finally, redirect every URI to index.htm exept of /home, /background.jpg, /icon.png and /fonts/segoeui.ttf

# Redirect (if not an existing file) to /index.htm (which will after redirect to /home)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.htm [R=301,L]