.htaccess 如果匹配模式则重定向,否则什么都不做
.htaccess redirect if match pattern else do nothing
我要满足三个场景
场景是
- 如果
www.example.com
则需要重定向到 www.example.com/a-a
- 如果
www.example.com/pages
则需要重定向到 www.example.com/a-a/pages
- 不需要重定向,如果
www.example.com/b-b
则按原样进行 www.example.com/b-b
- 不需要重定向,如果
www.example.com/b-b/pages
则按原样进行 www.example.com/b-b/pages
我的代码满足前两种情况并且强制始终相同。我不能带not条件。
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/ [L,R=301]
RewriteCond %{REQUEST_URI} ^/b-b(/.*)?$
RewriteRule ^(.*)$ [L,R=301] # do nothing here and not to do the previous condition
第二个条件总是强制www.example.com/a-a/b-b
我不想要这个。
第二条规则实际上没有做任何事情,因为对 /b-b
的请求被第一条规则捕捉到了。 (第二条规则无论如何都是无效的,因为您缺少 substitution 字符串,它会导致内部重写为 [L,R=301]
- 这可能会“可怕地破坏”。)
您不需要第二条规则。您可以使用 RewriteCond
指令在第一条规则上创建例外,就像您创建例外以排除 /a-a
(并重定向到自身)一样。
例如:
RewriteCond %{REQUEST_URI} !^/b-b(/.*)?$
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/ [L,R=301]
您需要在测试前清除浏览器缓存,因为错误的 (301 - permanent) 重定向到 /a-a/b-b
将被缓存。为避免缓存问题,请使用 302(临时)重定向进行测试。
我要满足三个场景
场景是
- 如果
www.example.com
则需要重定向到www.example.com/a-a
- 如果
www.example.com/pages
则需要重定向到www.example.com/a-a/pages
- 不需要重定向,如果
www.example.com/b-b
则按原样进行www.example.com/b-b
- 不需要重定向,如果
www.example.com/b-b/pages
则按原样进行www.example.com/b-b/pages
我的代码满足前两种情况并且强制始终相同。我不能带not条件。
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/ [L,R=301]
RewriteCond %{REQUEST_URI} ^/b-b(/.*)?$
RewriteRule ^(.*)$ [L,R=301] # do nothing here and not to do the previous condition
第二个条件总是强制www.example.com/a-a/b-b
我不想要这个。
第二条规则实际上没有做任何事情,因为对 /b-b
的请求被第一条规则捕捉到了。 (第二条规则无论如何都是无效的,因为您缺少 substitution 字符串,它会导致内部重写为 [L,R=301]
- 这可能会“可怕地破坏”。)
您不需要第二条规则。您可以使用 RewriteCond
指令在第一条规则上创建例外,就像您创建例外以排除 /a-a
(并重定向到自身)一样。
例如:
RewriteCond %{REQUEST_URI} !^/b-b(/.*)?$
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/ [L,R=301]
您需要在测试前清除浏览器缓存,因为错误的 (301 - permanent) 重定向到 /a-a/b-b
将被缓存。为避免缓存问题,请使用 302(临时)重定向进行测试。