如何使用 htaccess 重写 GET 参数

问题描述

我需要重写网址:

https://pieskowato.pl/posts.PHP?post=param

https://pieskowato.pl/posts/param

我找到了 htaccess 配置,它可以在本地主机上运行,​​但不能在生产环境中运行..

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,R=301,NC]
RewriteRule ^/post/([^/]*)$ /post.PHP?post=$1 [L]

网址 https://pieskowato.pl/post/dlaczego-warto-adoptowac-psa

托管 OVH.com

解决方法

根据您展示的样品,您可以尝试以下操作吗? 在测试您的网址之前,请务必清除浏览器缓存。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,R=301,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule ^(post)/([^/]*)$ /$1.php?post=$2 [NC,L]
,

就这样吧:

# important to turn off MultiViews
Options -MultiViews
RewriteEngine On

# fix css/js/images
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,NC]

# handle /post/anything
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^post/([^/]+)/?$ post.php?post=$1 [L,QSA,NC]