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

时间:2017-03-06 05:40:13

标签: php apache .htaccess redirect mod-rewrite

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

我意识到这个问题已被多次询问,虽然我有部分解决方案,但我没有一个所有活动部件都能正常工作的解决方案。

我有4种url

首先......(索引文件重定向)

http://localhost/myproject/index.php - 我想要... http://localhost/myproject

第二....(此解决方案在系统范围内是必需的 - 对于所有.php文件) http://localhost/myproject/views/forgotpassword.php - 我想要的 http://localhost/myproject/views/forgotpassword

第三......(系统范围内需要此解决方案 - 适用于所有/ views /文件) http://localhost/myproject/views/forgotpassword.php - 我想要的 http://localhost/myproject/forgotpassword

第四......(此解决方案仅适用于两个文件)

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

我想限制访问所有以前的名称和路径(我认为这是不可能的,因为这样做会使代码无效 - 即在执行此操作后无效)所以我认为将使用重定向,但如果可能的限制是必需的......

以下是我合并的.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} ^[A-Z]{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隐藏和重定向工作)休息视图文件夹删除和字符清理不起作用。我喜欢解决方案的第一部分,因为那时我不必修改我的代码,一切都保持不变......

1 个答案:

答案 0 :(得分:2)

通过一些重构,您的规则需要采用不同的顺序:

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} ^[A-Z]{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]