.htaccess将子目录重定向到root问题

时间:2016-05-25 22:27:19

标签: php apache .htaccess redirect mod-rewrite

我的主域名绑定到我的public_html文件夹,但我使用.htaccess重定向将根目录更改为文件夹中的子目录,以便更容易托管多个站点。例如:

RewriteEngine on 

RewriteCond %{HTTP_HOST} ^(www.)?example.com$ 
RewriteCond %{REQUEST_URI} !^/subdirectory/ 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /subdirectory/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$ 
RewriteRule ^(/)?$ subdirectory/ [L]

根目录中的.htaccess文件如下:

RewriteEngine on

# Change default directory page
DirectoryIndex /home/

# Remove .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)/$ $1.php [L]

# Ensure all directory URLs have a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]

# Same for HTTPS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]

# Redirect default error page to home page
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(/|error/)?$ /home/ [R=301,L]

# Error Documents
ErrorDocument 400 /error/?e=400
ErrorDocument 401 /error/?e=401
ErrorDocument 403 /error/?e=403
ErrorDocument 404 /error/?e=404
ErrorDocument 500 /error/?e=500

# Prevent viewing of htaccess file
<Files .htaccess>
    order allow,deny
    deny from all
</Files>

这很好用,但我认为这个和我的site1目录中的.htaccess文件存在问题。如果我输入URL,有时会重定向到example.com/site1。因此该网站在example.com和example.com/site1上显示完全相同,但我不希望它显示为example.com/site1。 site1目录中的第二个.htaccess文件如下所示。

{{1}}

我不确定我使用的各种重写规则是否会影响URL,但如果可以解决,我将不胜感激。

提前致谢,如果我的描述不是很好,我会道歉。

1 个答案:

答案 0 :(得分:1)

尝试

# Ensure all directory URLs have a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [QSA,L,R=301]

# Same for HTTPS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [QSA,L,R=301]

它对我有用。 %{REQUEST_URI}包含site1,因此请勿使用它。 QSA添加任何URL参数,例如?param1 = val1&amp; param2 = val2如果不使用它们,则可以省略QSA。 此外,在测试时将R = 301替换为R = 302(临时重定向),否则您的浏览器会记住该规则并且不会再次发送请求。

相关问题