.htaccess - 将带有查询参数的动态 URL 转换为静态 URL

标签 .htaccess mod-rewrite

对于我网站上的动态内容,我使用带有查询变量的 url

e.g. http://www.example.com/directory/?state=NJ&city=Wayne&zip=07474 or
     http://www.example.com/directory/index.php?state=NJ&city=Wayne&zip=07474 

我想将它们转换为对 seo 友好的静态 url
e.g. http://www.example.com/directory/Wayne-NJ-07474/

我研究了 SO,发现 htaccess 重写规则似乎是要走的路。

当涉及到 htaccess 结构时,我是一个菜鸟,我无法理解的是我是否仍然会获得与各个查询参数(即州、城市和 zip )相关联的数据。这意味着我仍然可以通过 _REQUEST() 访问它们吗?

如果有人能帮助我针对我的具体情况制定重写规则,我也将不胜感激。

最佳答案

您可以在 DOCUMENT_ROOT/.htaccess 中使用此代码文件:

RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+directory/(?:index\.php)\?state=([^\s&]+)&city=([^\s&]+)&zip=([^\s&]+)\s [NC]
RewriteRule ^ /directory/%2-%1-%3? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^directory/([^-/]+)-([^-/]+)-([^-/]+)/?$ directory/?state=$2&city=$1&zip=$3 [L,QSA,NC]

关于.htaccess - 将带有查询参数的动态 URL 转换为静态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081520/

相关文章:

.htaccess - 如何使用 htaccess 转发查询字符串?

asp.net - Mod Rewrite MS Hosting 通过显示短 URL 隐藏长烦人的 URL?

.htaccess - 如何使用 htaccess 和 mod_rewrite 在内部重定向所有内容?

regex - .htaccess:从 URL 中删除 public

php - 同时启用 PHP 解析器和 Include 语句

php - URL 重写破坏了到 css 的链接

apache - 如何将请求重定向到站点根目录上方的特定文件?

php - Mod_重写: How to see the variables content?

php - 使用 htaccess 重定向/重写

php - 在 wordpress 中使用 htaccess 更改查询字符串 url