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
504 views
in Technique[技术] by (71.8m points)

.htaccess - Redirect to 404 if .php extension is requested in URL

I currently have all my pages working without their .php extensions by using mod_rewrite. Such as:

www.mywebsite.com/noextension

However, how would I go about redirecting my users to a 404 page if they decide to add the .php extension to the url like this?

www.mywebsite.com/noextension.php

My htaccess looks like this so far:

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^([a-zA-Z0-9]+)(/)?$ $1.php
RewriteRule ^forums/([a-zA-Z0-9]+)(/)?$ forums.php?category=$1 [NC]

I have tried things such as this RewriteRule .php$ - [R=404], however, it just 404's every single page I go to. I assume I might have to use something like REQUEST_URI to do what I am asking.

What do you guys suggest I add? Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try these lines (place above those you have already):

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+).php - [F,L]

This rule will block (403 error) direct access to ANY .php file (but will path trough already rewritten URLs, when rule goes to next iteration).

TBH I'm not 100% sure that it will work (it depends on your Apache config) ... but considering that you have v2.2.x it should (it works fine on mine 2.2.17).


UPDATE: For "its kicking my web sites homepage without /index to a 404" add this line before the above rule:

RewriteRule ^$ /index.php [QSA,L]

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

...