rewriteengine 和 direct 结合 htaccess

rewriteengine and direct combine with htaccess

我有一个编码脚本显示 url 就像 example.com/pagename .

我想用rewriteengine来显示它example.com/page=pagename 并将 example.com/pagename 重定向到 example.com/ 以隐藏脚本类型代码 .

你能帮帮我吗?

是否可以将 `` 完全更改为 page= 之类的其他内容? 这正是我想要做的。

我已经尝试了一些代码,例如

RewriteEngine On
RewriteRule ^page\=([^/]*)$ / [L]

它正确显示 example.com/page=pagename 但您可以加载 example.com/pagenameexample.com/page=pagenamepagename

but you can load example.com/?a=pagename

为了防止这种情况,您还需要一个外部重定向到您想要的 URL(在您的内部重写之前)。为了防止重写循环,您可以检查 THE_REQUEST:

# Redirect typed URLs to the desired URLs
RewriteCond %{THE_REQUEST} \?a=([^\ ]*)
RewriteRule ^$ /page=%1? [R,L]

替换后的 ? 会删除原始查询字符串。 (一旦您对重定向感到满意,请将其更改为永久重定向,R=301。)

but you can load ... example.com/page=pagename?a=pagename

嗯,这是预料之中的。但是 page=pagename 将优先,而 ?a=pagename 将被您的重写删除。但是,拒绝这样的要求。 IE。仅在没有查询字符串时重写,然后使用条件修改现有规则:

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^page=([^/]*)$ /?a= [L]

这将导致 URL 触发 404。


UPDATE#1: 处理 example.com/pagename 的请求,而不是 example.com/page=pagename:

# Redirect "ugly" URLs to the desired URLs
RewriteCond %{THE_REQUEST} \?a=([^\ ]*)
RewriteRule ^$ /%1? [R,L]

# Internally rewrite the "pretty" URL to the real URL
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([^/]*)$ /?a= [L]

UPDATE#2: 上面的更严格的版本。这只允许 "pagename" 由字符 a-zA-Z0-9_-:

# Redirect "ugly" URLs to the desired URLs
RewriteCond %{THE_REQUEST} \?a=([\w-]*)
RewriteRule ^$ /%1? [R,L]

# Internally rewrite the "pretty" URL to the real URL
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([\w-]*)$ /?a= [L]