使用 .htaccess 的转发路径

Forwarding Path With .htaccess

我在 https://files.example.com 上使用 cPanel 托管,我希望 https://files.example.com/anything-here 重定向到我的主网站并转发路径,所以你最终会在 https://www.example.com/anything-here 上。这可能吗?

请注意,我的 .htaccess 文件中也有一个强制 SSL 重定向。

https://www.example.com 是一个 Google 站点。

我的 .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 is a Google Site.

如果这两个站点位于不同的服务器上,并且您只需要将所有内容从一台主机重定向到另一台主机并保持相同的 URL 路径,那么您的 .htaccess 文件位于 files.example.com,但以下 mod_alias Redirect 指令除外:

# 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]

参考:


更新:

But I just realised that it's also forwarding the path for files that do exist on my hosting. I onlt want it to forward invalid paths through to 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 的第一个条件(如果不需要)。