HTACCESS ModRewrite以隐藏额外的URL属性


HTACCESS ModRewrite to hide extra URL attributes

我有一个看起来像这样的URL: http://localhost/blog/web-design-for-speed/post/?pid=CMATWA6YTXT6LSKYVXE3已经使用了 ModRewrite 条件:

# rewrite URL from ?url=slug to /slug
RewriteEngine on
# BaseRewrite /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?url=$1 [L,QSA]
# redirect www to non www
RewriteCond %{HTTP_HOST} ^www'.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

上面的代码确实将 ?url= 更改为 blog/但是,我仍然只剩下 ?pid。我的问题是,是否可以隐藏 pid 但仍然可以使用 PHP 通过 _GET 美元访问它?

即使使用重写规则,PID 仍然需要传递给服务器,您可以实现的最好的办法是让 PID 作为虚拟目录结构的一部分出现在 URL 中,我使用以下方法实现了这一目的......

.htaccess

## No directory listings
IndexIgnore *
## Can be commented out if causes errors, see notes above.
Options +FollowSymlinks
Options -Indexes
## Mod_rewrite in use.
RewriteEngine On
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*'([^)]*') [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|'[|'%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|'[|'%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.
## Begin - Custom redirects
#
# If you need to redirect some pages, or set a canonical non-www to
# www redirect (or vice versa), place that code here. Ensure those
# redirects use the correct RewriteRule syntax and the [R=301,L] flags.
#
## End - Custom redirects

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_URI} !^/index'.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

在你的代码中,你所要做的就是获取超级全局的$_SERVER['REQUEST_URI']并解析它,使用 explode("/", $_SERVER['REQUEST_URI']) 分解它,然后你最终得到一个数组,URL 中的每个元素都有自己的数组索引从零开始,然后你可以把任何你想要的东西放入 URL 并通过分解数组访问它。