I use cPanel hosting on https://files.example.com
and I'd like https://files.example.com/anything-here
to redirect to my main website and forward the path, so you'd end up on https://www.example.com/anything-here
. Is this possible?
Note that I also have a forced SSL redirect inside my .htaccess
file.
https://www.example.com
is a Google Site.
My .htaccess
file:
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;"
CodePudding user response:
https://www.example.com
is a Google Site.
If the two sites are on different servers and you simply need to redirect everything from one host to the other and maintain the same URL-path then you don't appear to need anything in your .htaccess
file at files.example.com
except for the following mod_alias Redirect
directive:
# Redirect everything to https://www.example.com/ and maintain URL-path
Redirect 302 / https://www.example.com/
The Redirect
directive is prefix matching and everything after the match is copied onto the end of the target URL. So, a request for /foo
is redirected to https://www.example.com/foo
.
If, however, you have other hostnames pointing to your cPanel account then you'll need to use a mod_rewrite rule and check the requested hostname.
For example, at the end of your existing .htaccess
file:
# 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]
Reference:
- https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirect
- https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule
UPDATE:
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.
In that case, you'll need to do it like this instead:
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]
The 2nd and 3rd conditions check that the request does not map to an existing file (or directory) before issuing the redirect.
Remove the first condition that checks the HTTP_HOST
if it's not required.