.htaccess problems with https redirect

Viewed 325

I have just upgraded my website from HTTP to HTTPS and my .htaccess, which worked perfectly before, is now behaving strangely. I have the following in there:

  • Remove trailing slash
  • Remove php extension

...plus others, but I guess these are the problematic ones.

The behaviors I'm getting, on an example page, are:

Am I missing something obvious? Code is:

Order Deny,Allow

DirectoryIndex index.php

# Secure text files
<Files ~ "\.txt$">
  Order allow,deny
  Deny from all
</Files>

# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

ErrorDocument 404 /404.php

RewriteEngine On

# All calls go to SSL
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ https://www.navanter.com/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ https://www.navanter.com/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]
1 Answers

For this specific problem, your rewrite rules for removing the trailing / and the .php extension shouldn't need the full URL in the substitution. You might also consider reordering some of those rules.

Updated Example:

Require all granted

DirectoryIndex index.php

# Secure text files
<Files ~ "\.txt$">
  Require all denied
</Files>

ErrorDocument 404 /404.php

RewriteEngine On

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

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,R=301,L]

# Resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [NC,L]

A couple things to note here:

  • The directives above were modified to use the updated apache 2.4 syntax
  • The RewriteEngine on directive should come before the other rewrite rules
  • The HTTP -> HTTPS and non-www -> www redirect logic can be done in a single operation
  • The PHP extension stripping, and subsequent remapping, should be done without the full URL to avoid the duplication behavior you observed. This last bit should fix the problem.

If you need further info on some of the syntax employed here, you can check the mod_rewrite documentation.

Related