vendredi 4 septembre 2020

A better htaccess, less lines and same result, is it possible?

I'm no regex expert nor lover, but hey.. it's part of the job! After reading this article, I'm searching for a better solution (ie. less redirect, but same result) to do what I need to do. This article is almost what I want, except that I don't want a trailing slash and I dont't want a www.

In brief;

  1. Force SSL
  2. Force non-www
  3. Force a no-trailing slash policy
  4. Bonus : Force a no-trailing slash policy EXCEPT for the home page, which need to have a force trailing /

The expected result:

https://example.com ---> https://example.com/
http://www.example.com/hello/ ---> https://example.com/hello

Here's the "starter" I use, it works fine but may cause two 301 :

    # FORCE NON-WWW
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
    
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
    
    # FORCE SSL
    RewriteCond %{HTTPS} off 
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # FORCE NO-TRAILING SLASH POLICY
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

Thank you!




Aucun commentaire:

Enregistrer un commentaire