Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

apache - Redirect loop with simple htaccess rule

I have been pulling my air out over this. It worked before the server migration!

Ok so basically it's as simple as this:

I have a .php file that I want to view the content of using a SEO friendly URL via a ReWrite rule.

Also to canonicalise and to prevent duplicate content I want to 301 the .php version to the SEO friendly version.

This is what I used and has always worked till now on the new server:

RewriteRule ^friendly-url/$ friendly-url.php [L,NC]
RewriteRule ^friendly-url.php$ /friendly-url/$1 [R=301,L]

However disaster has struck and now it causes a redirect loop.

Logically I can only assume that in this version of Apache it is tripping up as it's seeing that the script being run is the .php version and so it tries the redirect again.

How can I re-work this to make it work? Or is there a config I need to switch in WHM?

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is how your .htaccess should look like:

Options +FollowSymLinks -MultiViews 

RewriteEngine On
RewriteBase /

# To externally redirect /friendly-url.php to /friendly-url/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}s/+(friendly-url).php [NC]
RewriteRule ^ /%1/? [R=302,L]

## To internally redirect /anything/ to /anything.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/$ $1.php [L]

Note how I am using R=302, because I don't want the rule to cache on my browser until I confirm its working as expected, then, once I can confirm its working as expected I switch from R=302 to R=301.

Keep in mind you may have also been cached from previous attempts since you're using R=301, so you better of trying to access it from a different browser you have used just to make sure its working.

However disaster has struck and now it causes a redirect loop.

It causes a redirect loop because your redirecting it to itself, the different on my code is that I capture the request, and redirect the php files from there to make it friendly and then use the internal redirect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...