php - .htaccess 重写多个参数的规则

标签 php .htaccess url-rewriting rewrite url-routing

重写以下 3 个 URL
http://example.com/index.php?page=searchhttp://example.com/searchhttp://example.com/index.php?page=profile&value=mynamehttp://example.com/mynamehttp://example.com/index.php?page=stats&type=dailyhttp://example.com/stats/daily
当前的 .htaccess 写成如下:

Options -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+)&value=([^\s&]+) [NC]
RewriteRule ^ index/%1/%2? [R=302,L,NE]

RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+)&type=([^\s&]+) [NC]
RewriteRule ^ index/%1/%2? [R=302,L,NE]

RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+) [NC]
RewriteRule ^ index/%1/? [R=302,L,NE]

RewriteRule ^index/([^/]+)/([^/]+)/?$ /index.php?page=$1&value=$2 [NC,L,QSA]
RewriteRule ^index/([^/]+)/([^/]+)/?$ /index.php?page=$1&type=$2 [NC,L,QSA]
RewriteRule ^index/([^/]+)/?$ /index.php?page=$1 [NC,L,QSA]

我需要从第一个和第三个 URL 中删除/index/,并从第二个 URL 中删除/index/profile/。

欢迎所有意见和建议。

最佳答案

您不能让搜索和配置文件都使用相同的正则表达式模式。例如,如果有人要求:

http://example.com/index/foo

他们是要访问名为“foo”的页面还是访问名为“foo”的用户的个人资料?您需要添加一些将两者分开的内容,例如:
Options -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /index\.php\?page=profile&value=([^\s&]+) [NC]
RewriteRule ^ profile/%1? [R=302,L,NE]

RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+)&type=([^\s&]+) [NC]
RewriteRule ^ page/%1/%2? [R=302,L,NE]

RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+)(\ |$) [NC]
RewriteRule ^ page/%1? [R=302,L,NE]

RewriteRule ^profile/([^/]+)/?$ /index.php?page=profile&value=$1 [NC,L,QSA]
RewriteRule ^page/([^/]+)/([^/]+)/?$ /index.php?page=$1&type=$2 [NC,L,QSA]
RewriteRule ^page/([^/]+)/?$ /index.php?page=$1 [NC,L,QSA]

这使您的网址看起来像:
http://example.com/profile/myname

http://example.com/page/search

http://example.com/page/stats/daily

关于php - .htaccess 重写多个参数的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31707127/

相关文章:

php - 未知列 'STRICT_ALL_TABLES,' 设置 CodeIgniter DB 连接

php - While 循环遍历 mysql 数据库列表

wordpress - mod_rewrite : if/else type RewriteRule

apache - HTACCESS 导致错误 404

wordpress - 从 HTTP 重定向到 HTTPS 删除 url 中的斜杠

java - Spring MVC Controller 更改 URL 或发出错误的 URL

PHP文件上传: mime or extension based verification?

php - Codeigniter 迁移自动和 key 问题

php - .htaccess 使文件夹充当根目录?

Spring Web Flow 和 Url Rewrite Filter——清理 URL