.htaccess规则,在url中重写密钥

时间:2013-03-20 13:41:12

标签: .htaccess mod-rewrite

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

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

总是像网址一样:

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

1 个答案:

答案 0 :(得分:2)

需要在RewriteCond中捕获查询字符串参数。您可以匹配(theme|type)并捕获该值,然后使用(theme|type)_of_site中的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]