skip to Main Content

In .htaccess file:

# Enable mod_rewrite
RewriteEngine on

# Rewrite file name
RewriteRule ^dome.htm$ dome.php [L,QSA]


# Force www
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Forced SSL & WWW works good except rewrite filename where request made from below URL it return to real file name which https://www.example.com/dome.php:

example.com/dome.htm
www.example.com/dome.htm
https://example.com/home.htm

How to keep https://www.example.com/dome.htm when access above URL.

2

Answers


  1. Chosen as BEST ANSWER

    Easy:

    RewriteRule    ^dome.htm?$    dome.php [NC,L]    # Handle requests for "dome"
    

  2. You need to change the order of processing:

    # Enable mod_rewrite
    RewriteEngine on
    
    # Force www
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    # Force SSL
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
    
    # Rewrite file name
    RewriteRule ^dome.htm$ dome.php [L,QSA]
    

    Also note the slightly modified regular expression in that RewriteRule 😉

    Why does this make a difference? Imagine an incoming request getting rewritten… With your order of rules the request first gets rewritten to /dome.php, then redirected to https://%{HTTP_HOST}%{REQUEST_URI}, which will instruct the browser to load /dome.php from that new URL… RewriteRules are processed from top to bottom. Sure, you specified the [L] flag, however that only ends the rewriting _for that iteration! If the last iteration changed the request (a rewriting was performed), then another iteration is done by the http server.

    An alternative would be to leave your order of rules but use the [END] flag instead of [L] which does what you want. But it is only supported on newer versions of the apache http server, from version 2.4 onwards.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search