仅当找不到页面时,htaccess才会静默地从另一个子域提供页面

时间:2018-03-09 10:55:04

标签: .htaccess mod-rewrite

我的主页位于" main.mysite.com"。 客户访问网站由" customer.mysite.com"它只包含主页的一个子集。 当客户请求页面" customer.mysite.com/data.php"时,我想首先检查文件是否在" customer.mysite.com"子域名,如果是,则提供该页面,如果没有,则在" main.mysite.com/data.php"子域。 我还想把网址保存在" customer.mysite.com/data.php"对于这两个案例。

目前我的完整htaccess文件是:

# This will enable the Rewrite capabilities
RewriteEngine On
RewriteBase /

# This rule will convert request urls like  /category/page?id=1  to  /?c=category&p=page&id=1
# Redirect to main page, which is Single Page Application and then manage to open the new tab
RewriteRule   ^([A-Za-z]*)\/([A-Za-z]*)([?]?[A-Za-z0-9=&]*)$   /?c=$1&p=$2   [NC,R,QSA]    

# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context
# First, this checks to make sure the connection is not already HTTPS
RewriteCond   %{HTTPS}   !=on
RewriteRule   ^/?(.*)   https://%{SERVER_NAME}/$1   [NC] 

# This rule will serve pages from  main.mysite.com  when browsed with  customer.mysite.com
# By removing the [R=301], it makes an internal redirect, keeping the original url in the browser
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ https://main.mysite.com/$1 [L,NC,QSA]

# Disable Directory Listing
Options -Indexes

<Files .htaccess>   
order allow,deny    
deny from all   
</Files>    

然而,当我浏览&#34; customer.mysite.com/page.php"时,我被重定向到&#34; main.mysite.com/page.php" ;,这不是什么我想要。

2 个答案:

答案 0 :(得分:2)

首先,将/category/page?id=1重定向到/?c=category&p=page&id=1

RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule   ^([A-Za-z]+)\/([A-Za-z]+)$   /?c=$1&p=$2   [NC,R=301,QSA] 

更改此内容:RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [NC]

到此RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]

因为%{HTTP_HOST}是包含目标主机的请求标头

此外:

我是你处理过这样的错误文件,当没有文件时会发生目标循环,所以最好这样处理:

替换这个:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ https://main.mysite.com/$1 [L,NC,QSA]

有了这个:

RewriteCond %{HTTP_HOST} !^(www\.)?main.mysite.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ https://main.mysite.com/$1 [L,NC,QSA]
#then you could handle the error that not found in main by this
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /path/to/error/page [L]

答案 1 :(得分:0)

通过向规则添加代理标志[P],服务器进行内部重定向,保持浏览器URL不变。通常,这可以通过不指定R = 301标志来工作,但是当规则正在改变域/子域时它不够。

什么有效:

RewriteRule ^(.*)$ https://main.mysite.com/$1 [P,L,NC,QSA]

请注意,P不需要L标志,因为它是隐含添加的,因为之后不能执行其他规则。