我在https://files.example.com
上使用cPanel托管,我希望https://files.example.com/anything-here
重定向到我的主要网站并转发路径,所以你最终会在https://www.example.com/anything-here
上。这可能吗?
请注意,我在.htaccess
文件中也有一个强制SSL重定向。
https://www.example.com
是一个谷歌网站。
我的.htaccess
文件:
ErrorDocument 400 /index.html
ErrorDocument 401 /index.html
ErrorDocument 403 /index.html
ErrorDocument 404 /index.html
ErrorDocument 500 /index.html
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Header always set Content-Security-Policy "upgrade-insecure-requests;"
https://www.example.com
是一个Google站点。
如果两个站点在不同的服务器上,你只需要将所有内容从一个主机重定向到另一个主机并保持相同的url路径,那么你似乎不需要在files.example.com
的.htaccess
文件中任何东西,除了以下mod_aliasRedirect
指令:
# Redirect everything to https://www.example.com/ and maintain URL-path
Redirect 302 / https://www.example.com/
Redirect
指令是前缀匹配,匹配后的所有内容都被复制到目标URL的末尾。因此,对/foo
的请求被重定向到https://www.example.com/foo
。
然而,如果你有其他主机名指向你的cPanel帐户,那么你需要使用mod_rewrite规则并检查请求的主机名。
例如,在现有.htaccess
文件的末尾:
# Redirect every request for "files.example.com"
# to https://www.example.com/ and maintain URL-path
RewriteCond %{HTTP_HOST} ^files.example.com [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=302,L]
参考:
- https://httpd.apache.org/docs/2.4/mod/mod_alias.html定向
- https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html rewriterule
UPDATE # 1:
但是我刚刚意识到它也在转发我主机上存在的文件的路径。我只希望它转发无效的路径到www.example.com。
在这种情况下,您需要这样做:
RewriteCond %{HTTP_HOST} ^files.example.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=302,L]
第二个和第三个条件在发出重定向之前检查请求没有映射到现有文件(或目录)。
删除HTTP_HOST
不需要的第一个检查条件。
更新# 2:
有没有办法让它排除"/URL"从这个吗?如果"URL"在路径(example.com/URL/whatever)中指定,那么我不希望这个。htaccess规则发生。我只是想让它对这个路径使用我的ErrorDocuments。
如果它只是一个模式你想要排除,即:所有以/URL
开头的url,那么你可以只修改RewritRule
指令。例如:
:
RewriteRule !^URL https://www.example.com%{REQUEST_URI} [R=302,L]
不以/URL
开头的url将被排除。注意,这还包括/URLwhatever
,而不仅仅是/URL/whatever
。