9

I'm trying to create clean URLs on my website. Now I succeeded in configuring apache so every request like mysite.com/page will work. But I also want that requests for mysite.com/page.php will be redirected to mysite.com/page. I've set environment variable in .htaccess to check if i already been redirected to prevent loops, but i still get them... Here's the .htaccess:

<IfModule mod_rewrite.c>
Options +FollowSymlinks

RewriteEngine On
RewriteBase /

# set the variable
RewriteRule ^$ - [L]
RewriteRule ^(.*)$ $1 [E=REWROTE:0]

# this works fine
# make mysite.com/page work and set REWROTE variable to 1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L,E=REWROTE:1]

# but if i enable this, i get redirected and then stuck in a loop
# redirect mysite.com/page.php to mysite.com/page , but only if REWROTE not 1
#RewriteCond %{ENV:REWROTE} !^1$
#RewriteRule ^(.*)\.php$ $1 [R=301,L]

Thanks!

leonidx86
  • 93
  • 1
  • 5
  • Welcome to stack overflow. Thanks for wording your question clearly, providing code, and showing what works and what doesn't. If you have useful information in your apache logs, please post that, too. Sometimes the redirect issues become more obvious when you see the logs. – Michael Haren Jan 31 '09 at 16:20
  • Unfortunately i don't have access to that kind of information. – leonidx86 Jan 31 '09 at 16:45

4 Answers4

14

Add this rule above your existing rewrite rules to stop redirecting if the request has already been redirected once (ref):

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]
Michael Haren
  • 105,752
  • 40
  • 168
  • 205
1

You could check the request line for what has originally been requested:

RewriteCond %{THE_REQUEST} ^[A-Z]+\ (/[^\ ]*)\.php[?\ ]
RewriteRule \.php$ %1 [R=301,L]

Oh, and the first argument of the RewriteCond directive is not a regular expression but just a string. So the escaping the . is wrong.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

another quick & dirty way to prevent looping in these situations i've found is to add a querystring and then check for its existence in the redirect.

RewriteCond %{QUERY_STRING} !a=a
RewriteRule ^(.*)\.php$ %1 [NC,R=301,L]
RewriteRule ^(.*)$ $1.php?a=a [NC,L]

found on this site: http://answers.oreilly.com/topic/542-how-to-properly-redirect-for-maximum-seo/

cazz
  • 1
  • 2
0

Is there some reason why you can't use the end-of-string termination character, $ ?

RewriteRule ^/(.+)\.php$ /$1

will redirect /page.php to /page but will not do any redirecting on /page .

Fundamentally, using techniques like setting environment variables and adding checks for REDIRECT_STATUS is not going to be very robust.

fooquency
  • 1,575
  • 3
  • 16
  • 29