.htaccess URL 重写为多参数项

.htaccess URL 重写为多参数项

我刚刚在这件事上花了我生命中的最后 10 个小时,并且一直在奔波,所以希望有人能够帮助我。

我想要像这样加载特定的 URL:

http://example.com/f/2011/image.png?attribute=small

当出现如下格式的 URL 时,我希望将其重写为以下格式访问服务器:

http://example.com/generate.php?f=2011/image.png&attribute=small

基于以上内容,我的问题有两个:

  1. 我该如何重写 htaccess 中的 URL 来满足上述要求?
  2. 如果原始 URL 没有属性查询字符串参数,那么如何确保当它通过 htaccess 访问服务器时属性将为 false/blank/等等?

答案1

RewriteEngine On
# If it's not an existing file...
RewriteCond %{REQUEST_FILENAME} !-f
# ...and it's not an existing directory...
RewriteCond %{REQUEST_FILENAME} !-d
# ...and it starts with "f/" then rewrite it to generate.php
RewriteRule ^f/(.*)$ generate.php?f=$1 [L,QSA]

两者RewriteCond可以省略。更多信息:

重写规则

QSA 标志

答案2

RewriteEngine On

RewriteRule ^([a-z]+)/([0-9]+)/image.png?attribute=small$ generate.php?f=$2/image.png&attribute=small&%{QUERY_STRING} [L]

答案3

以下是更有可能发挥作用的方法:

RewriteEngine On
# If it's not an existing file...
RewriteCond %{REQUEST_FILENAME} !-f
# ...and it's not an existing directory...
RewriteCond %{REQUEST_FILENAME} !-d
# ...and it starts with "f/" then rewrite it to generate.php
RewriteRule ^([a-z]+)/([0-9]+)/image\.png$ /generate.php?f=$1 [QSA,L]

请告诉我是否有效

相关内容