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

Categories

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

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

1 Answer

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...