所以,总结一下:
- 两个域指向同一个网站:
example.com 和 example.dev
- 某些 URL 应该只能通过
example.com 访问(如果没有,请重定向)。
- 一些 URL 应该可以在两个域中访问(无重定向)
- 否则,将所有请求重定向到
example.dev。
在您的根 .htaccess 文件的顶部尝试以下操作,在 WordPress 前端控制器之前。
我们可以使用TARGET_DOMAIN 环境变量来设置应该通过哪个域(如果有)访问特定的 URL,然后稍后使用它来触发重定向。
# Prevent rewritten requests (to the WP front-controller) from being redirected
RewriteCond %{ENV:REDIRECT_STATUS} .
RewriteRule ^ - [L]
# The TARGET_DOMAIN environment variable holds the desired target domain (if any)
# - for the requested URL
# eg. "example.com" or "example.dev" or empty for no redirect / accessible from both.
# Set the "default" target domain
# - Any URLs not listed below will redirect to this domain
RewriteRule ^ - [E=TARGET_DOMAIN:example.dev]
# URLs that should be redirected to (or remain at) the other domain
RewriteCond %{REQUEST_URI} ^/bio [OR]
RewriteCond %{REQUEST_URI} ^/computing [OR]
RewriteCond %{REQUEST_URI} ^/contact [OR]
RewriteCond %{REQUEST_URI} ^/donate [OR]
RewriteCond %{REQUEST_URI} ^/encrypt [OR]
RewriteCond %{REQUEST_URI} ^/genderless-pronouns [OR]
RewriteCond %{REQUEST_URI} ^/gnu-linux-controversy [OR]
RewriteCond %{REQUEST_URI} ^/legal [OR]
RewriteCond %{REQUEST_URI} ^/readings [OR]
RewriteCond %{REQUEST_URI} ^/now
RewriteRule ^ - [E=TARGET_DOMAIN:example.com]
# URLs that should not be redirected - accessible from both domains
# - Sets TARGET_DOMAIN to empty string (ie. no target domain)
# - Must also exclude static resources (images, CSS, JS, etc.) from being redirected
RewriteCond %{REQUEST_URI} ^/login [OR]
RewriteCond %{REQUEST_URI} ^/admin [OR]
RewriteCond %{REQUEST_URI} ^/wp-admin [OR]
RewriteCond %{REQUEST_URI} ^/wp-login [OR]
RewriteCond %{REQUEST_URI} \.(php|css|js|jpg|gif|webp)$ [NC,OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [E=TARGET_DOMAIN]
# Redirect to the desired TARGET_DOMAIN (if any)
# - if not already at the TARGET_DOMAIN
RewriteCond %{ENV:TARGET_DOMAIN} .
RewriteCond %{HTTP_HOST}@@%{ENV:TARGET_DOMAIN} !^([a-z0-9.-]+)@@\1$
RewriteRule ^ https://%{ENV:TARGET_DOMAIN}%{REQUEST_URI} [R=302,L]
补充说明:
RewriteCond %{REQUEST_URI} ^/bio [OR]
我已经回到使用正则表达式 (regex) 匹配。这以额外的复杂性为代价为您提供了最大的灵活性(尽管您可以将两者混合使用)。以上匹配任何以/bio开头的URL。因此,它也将匹配 /bio/ 和 /bioanything。仅使用字符串结尾锚 ($) 匹配 /bio。例如。 ^/bio$.
需要使用正则表达式来避免重定向任何 开始 /wp-admin.
的 URL
RewriteCond %{REQUEST_URI} \.(php|css|js|jpg|gif|webp)$ [NC,OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [E=TARGET_DOMAIN]
请注意,除了某些请求的 URL(/login、/admin 等)之外,静态资源(图像、CSS、JS 等)也需要被排除在重定向之外。
RewriteCond %{ENV:TARGET_DOMAIN} .
RewriteCond %{HTTP_HOST}@@%{ENV:TARGET_DOMAIN} !^([a-z0-9.-]+)@@\1$
RewriteRule ^ https://%{ENV:TARGET_DOMAIN}%{REQUEST_URI} [R=302,L]
第一个条件确保我们只在设置了目标域时尝试重定向。第二个条件检查当前请求的域(即Host 标头)是否与TARGET_DOMAIN 不同。如果这两项检查都成功,则它会重定向到同一 URL 上的目标域。
在测试之前确保您的浏览器缓存已清除,并首先使用 302(临时)重定向进行测试以避免潜在的缓存问题。