tmrhmdv
tmrhmdv

Reputation: 172

Apache mod_rewrite is not working

I am trying to redirect requests to http://www.site.com/customer to https://www.site.com/customer and hide .php extensions, but it's not working. These are my configuration files:

httpd.conf:

LoadModule rewrite_module modules/mod_rewrite.so

mysite.conf:

<Directory /var/www/site/customer>
  Order Deny,Allow
  Allow from all
</Directory>
Alias /customer /var/www/site/customer

.htaccess in /var/www/site/customer:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}

#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([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.*)\.php$ $1 [R=301,L]

#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

Am I missing something?

Upvotes: 0

Views: 333

Answers (1)

Olivier Pons
Olivier Pons

Reputation: 15816

Yep you are missing something ;)

Here are some modifications:

  • you forgot the redirect and last tag in HTTPS rule
  • you forgot the QSA directive to keep the query string when there's a redirect

So here it is, this might help, but maybe won't work 100% (but it's far still better than it was anyway):

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://$1 [QSA,NC,L]

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

#redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.*)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.*)\.php$ $1 [QSA,R=301,L]

#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

Two hints:

If you're not in a hosted environment (= if it's your own server and you can modify the virtual hosts, not only the .htaccess files), try to use the RewriteLog directive: it helps you to track down such problems:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

My favorite tool to check for regexp:

http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)

Upvotes: 2

Related Questions