【问题标题】:URL Rewriting Using .htaccess for PHP使用 PHP 的 .htaccess 重写 URL
【发布时间】:2022-01-08 22:40:39
【问题描述】:
我想将此网址example.com/post.php?id=12345&title=xyz 转换为example.com/12345/xyz。
我可以使用example.com/12345,但无法获得/xyz。
RewriteEngine On
RewriteRule ^post/([a-zA-Z0-9-/]+)$ post.php?id=$1
RewriteRule ^post/([a-zA-Z-0-9-]+)/ post.php?id=$1
【问题讨论】:
标签:
apache
.htaccess
url
mod-rewrite
friendly-url
【解决方案1】:
使用您显示的示例,请尝试遵循 htaccess 规则。请确保在测试您的 URL 之前清除您的浏览器缓存。
此解决方案假定您在浏览器中点击 example.com/post.php?id=12345&title=xyz 示例 url 并希望将其更改为 example.com/12345/xyz
##Enabling engine here.
RewriteEngine ON
##Extrenal redirect 301 to mentioned url by OP in question.
RewriteCond %{THE_REQUEST} \s/post\.php\?id=([^&]*)&title=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]
##Internal rewrite to post.php with query strings.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/?$ post.php?id=$1&title=$2 [QSA,L]