Rewrite for an empty query string

2019-04-18 16:43发布

I'm building in some caching to one of my sites, and I can't seem to find if there's a way to add a condition with mod_rewrite to apply only if the query string on a request is empty.

For example, I'd love to know if I can have a request with no query string like

http://www.example.com/

load the page at

http://www.example.com/index.home.html

But any request with a query string, such as

http://www.example.com/?id=32

to load normally and not be affected by the rewrite.

What am I missing?

3条回答
Animai°情兽
2楼-- · 2019-04-18 17:10

i know this ones pretty old, but better alternative is:

RewriteCond %{QUERY_STRING} -n
RewriteRule ^/$ /index.home.html
查看更多
劫难
3楼-- · 2019-04-18 17:20

To match against empty QueryString , we use ^$ in our Condition Pattern. The following rule redirects /file.html to /file2.html but it fails to redirect /file.html?querystring because of the condition.

RewriteEngine on

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/?file.html$ /file2.html? [L,R]

An empty question mark at the end of the Rule is important as it discards the old querystring otherwise the redirected url will look like /file2.html?querystring .

Or alternatively: RewriteEngine on

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/?file.html$ /file2.html [L,R,QSD]

The QSD flag don't keep the query string if there is one.

查看更多
劳资没心,怎么记你
4楼-- · 2019-04-18 17:23

I figured it out. This seems to do the trick pretty well:

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/$ /index.home.html

Of course, if there's a better way, I'd love to hear it.

查看更多
登录 后发表回答