开发者

Redirect to 404 if .php extension is requested in URL

开发者 https://www.devze.com 2023-03-20 00:32 出处:网络
I currently have all my pages working without their .php extensions by using mod_rewrite. Such as: www.mywebsite.com/noextension

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开发者_如何学Python I might have to use something like REQUEST_URI to do what I am asking.

What do you guys suggest I add? Thanks.


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消