使用.htaccess在多个条件下的URL重写/redirect/限制

服务器版本:Apache / 2.4.18(Win32)OpenSSL / 1.0.2e PHP / 7.0.8

我意识到这个问题已经被问了很多次了,虽然我有解决scheme,但是我没有解决scheme,所有的移动部件都能正常工作。

我有4种types的url

首先…(索引文件redirect

http://localhost/myproject/index.php – 我想要… http:// localhost / myproject

第二….(这种解决scheme是必需的系统范围内的所有.php文件) http://localhost/myproject/views/forgotpassword.php – 我想作为http:// localhost / myproject / views /忘记密码

第三…(这个解决scheme是全系统需要的 – 所有/视图/文件) http://localhost/myproject/views/forgotpassword.php – 我想要的http:// localhost / myproject /忘记密码

第四…(这个解决scheme只适用于两个文件)

http://localhost/myproject/views/propertydetail.php?property_id = 4 – 我想要的http:// localhost / myproject / property / 4

我想限制访问所有以前的名称和path(我认为这是不可能的,因为这样做会导致代码无法正常工作 – 即没有这样做后)所以我认为redirect将被使用,但如果可能的限制是必需的。 ..

以下是我的整合.htaccess文件

 Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / ## hide .php extension ## To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[AZ]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L,NC] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [L] ## hide views folder RewriteRule ^$ views/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ views/$1 ## remove special characters and clean the urls RewriteRule ^property/([0-9]+) views/propertydetail.php?property_id=$1 RewriteRule ^user/([0-9]+) views/viewprofile.php?profile_id=$1 

与此只有第一部分(PHP隐藏和redirect工作)rest意见文件夹删除和字符清理不工作。 我喜欢解决scheme的第一部分,因为那样我就不必修改我的代码了,一切都保持不变。

通过一些重构,你的规则需要按照不同的顺序进行:

 ErrorDocument 404 default Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase /myproject/ ## hide .php extension ## To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[AZ]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R=301,L,NE] ## remove special characters and clean the urls RewriteRule ^property/(\d+)/?$ views/propertydetail.php?property_id=$1 [L,QSA,NC] RewriteRule ^user/(\d+)/?$ views/viewprofile.php?profile_id=$1 [L,QSA,NC] ## hide views folder RewriteRule ^$ views/ [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(?!view/)(.*)$ views/$1 [L,NC] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.+?)/? $1.php [L]