3

假设我们有一个这样的网址:

http://domain.com/?theme_of_site=parameter_value
http://domain.com/?type_of_site=parameter_value
  • domain.com - 稳定/静态,始终相同
  • theme_of_site & type_of_site - 稳定/静态,选择时相同
  • 参数值- 动态

就像总是有这样的网址:

http://domain.com/?theme=parameter_value
http://domain.com/?type=parameter_value

我怎样才能在 .htaccess 中写这个?


对于以下讨论:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Start by redirecting the original links from type_of_site= to type=
# Only if the browser's original request contains the strings
RewriteCond %{THE_REQUEST} theme_of_site=([^&]+)
RewriteCond %{THE_REQUEST} type_of_site=([^&]+)
RewriteRule (.*) $1?theme=%1&type=%2 [L,R=301]

RewriteCond %{THE_REQUEST} theme_of_site=([^&]+)
RewriteRule (.*) $1?theme=%1 [L,R=301]

RewriteCond %{THE_REQUEST} type_of_site=([^&]+)    
RewriteRule (.*) $1?type=%1 [L,R=301]

# Then, after performing the initial redirects to change the browser
# URL, rewrite the parameters internally

# Match both present:
RewriteCond %{QUERY_STRING} theme=([^&]+)
RewriteCond %{QUERY_STRING} type=([^&]+)
RewriteRule (.*) $1?theme_of_site=%1&type_of_site=%2 [L]

# Then match each individually
RewriteCond %{QUERY_STRING} theme=([^&]+)
RewriteRule (.*) $1?theme_of_site=%1 [L]

RewriteCond %{QUERY_STRING} type=([^&]+)
RewriteRule (.*) $1?type_of_site=%1 [L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
4

1 回答 1

2

查询字符串参数需要在RewriteCond. 您可以匹配(theme|type)并捕获该值,然后在内部使用(theme|type)_of_sitein a重写它RewriteRule

RewriteEngine On
# Match the theme or type paramater in `%1` and capture its value in `%2`
RewriteCond %{QUERY_STRING} (theme|type)=([^&]+)
# Rewrite The parameter name to include _of_site using the values captured above
# for all URLs as captured in $1
RewriteRule (.*) $1?%1_of_site=%2 [L]

上面的简单示例仅在指定一参数时才有效。如果您需要能够同时处理两者,就像example.com/?type=abc&theme=123它变得有点复杂一样:

# Start by redirecting the original links from type_of_site= to type=
# Only if the browser's original request contains the strings
RewriteCond %{THE_REQUEST} theme_of_site=([^&]+)
RewriteCond %{THE_REQUEST} type_of_site=([^&]+)
RewriteRule (.*) $1?theme=%1&type=%2 [L,R=301]

RewriteCond %{THE_REQUEST} theme_of_site=([^&]+)
RewriteRule (.*) $1?theme=%1 [L,R=301]

RewriteCond %{THE_REQUEST} type_of_site=([^&]+)    
RewriteRule (.*) $1?type=%1 [L,R=301]

# Then, after performing the initial redirects to change the browser
# URL, rewrite the parameters internally

# Match both present:
RewriteCond %{QUERY_STRING} theme=([^&]+)
RewriteCond %{QUERY_STRING} type=([^&]+)
RewriteRule (.*) $1?theme_of_site=%1&type_of_site=%2 [L]

# Then match each individually
RewriteCond %{QUERY_STRING} theme=([^&]+)
RewriteRule (.*) $1?theme_of_site=%1 [L]

RewriteCond %{QUERY_STRING} type=([^&]+)
RewriteRule (.*) $1?type_of_site=%1 [L]
于 2013-03-20T13:48:09.890 回答