4
\$\begingroup\$

Is there anything I could do to improve the following .htaccess code?

Options +FollowSymLinks

RewriteEngine On

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

# Redirect trailing slash to non-trailing slash.
# http://www.{domain}/foo/
# http://www.{domain}/foo
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

# Redirect trailing ".php" to extensionless.
# http://www.{domain}/foo.php
# http://www.{domain}/foo
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+ [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.php$ /$1 [R=301,L]

# Redirect "/index" to root.
# http://www.{domain}/index
# http://www.{domain}/
RewriteRule ^index$ / [NC,R=301,L]

# Forward to version with ".php" extension.
# http://www.{domain}/foo
# http://www.{domain}/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ /$1.php [L]
\$\endgroup\$
1
\$\begingroup\$

You can compress the www redirection to:

RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1|www\.) [NC]
RewriteCond %{REMOTE_ADDR} !=(127\.0\.0\.1|::1)
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

When redirecting .php to extensionless pages, you are not considering the query strings, which can be handled as follows (unless you do not want to do so):

RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.php$ /$1 [R=301,L,NC,QSA]

While adding QSA is not required, you should practice putting the flag as it might later on help you deal with infinite recursions. The same QSA can be added to the last rule, where you put back the .php extensions.

\$\endgroup\$
1
\$\begingroup\$

Use of %{THE_REQUEST} isn't idiomatic, and I don't see any purpose for the first RewriteCond in

# Redirect trailing ".php" to extensionless.
# http://www.{domain}/foo.php
# http://www.{domain}/foo
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+ [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.php$ /$1 [R=301,L]
\$\endgroup\$
3
  • \$\begingroup\$ If I remove the first RewriteCond in there, I get an ERR_TOO_MANY_REDIRECTS error from Chrome. \$\endgroup\$ – Kid Diamond Oct 6 '15 at 17:22
  • \$\begingroup\$ @KidDiamond You probably have Options MultiViews enabled. disable it. \$\endgroup\$ – hjpotter92 Oct 8 '15 at 5:30
  • \$\begingroup\$ @hjpotter92 Tried disabling it in my .htaccess. It didn't work. \$\endgroup\$ – Kid Diamond Oct 8 '15 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.