可通过多个URL访问的网站

时间:2018-10-22 13:13:29

标签: .htaccess redirect mod-rewrite url-rewriting silex

我正在VPS托管的网站上使用Silex微型框架。

因此,站点文件位于/site_name/public_html/文件夹中,但是对于Silex,站点必须指向/site_name/public_html/web/文件夹。

public_html目录中,我有以下.htaccess文件:

Options -Indexes -MultiViews

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Redirect to https & www
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]

    # Redirect incoming URLs to web folder
    RewriteCond %{REQUEST_URI} !web/
    RewriteRule (.*) /web/$1 [L]
</IfModule>

然后,在/public_html/web/文件夹中,以下.htaccess

<IfModule mod_rewrite.c>
    # Redirect incoming URLs to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

现在,一切正常,但是可以通过三种不同的模式访问我的页面:

  1. example.com/page/(我要保留的那个)
  2. example.com/web/page/
  3. example.com/web/index.php/page/

我已使用元规范来避免重复的内容,但我仍然希望后两个选项不存在。

我想我的两个.htaccess文件都需要更改,但是找不到。

1 个答案:

答案 0 :(得分:0)

实际上,我将完全删除.htaccess子目录中的/web文件,并直接重写为根/web/index.php文件中的.htaccess。通过拥有两个.htaccess文件,您似乎正在创建额外的工作。子目录中的mod_rewrite指令将完全覆盖父指令(默认情况下),因此您的规范HTTPS和www重定向也将被覆盖。

(假设您在RewriteEngine On文件中有一个/web/.htaccess指令?)

已删除/web/.htaccess文件,请在根.htaccess文件中尝试以下操作:

Options -Indexes -MultiViews

RewriteEngine On
RewriteBase /web

# Redirect to https & www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=302,L,NE]

# If /web or /index.php is present at the start of the requested URL then remove it (via redirect)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(?:web|index\.php)/(.*) /$1 [R=302,L]

# Front-controller...
# Internally rewrite all requests to /web/index.php (uses RewriteBase set above)
RewriteRule index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

通过对REDIRECT_STATUS环境变量的检查,可以确保我们仅测试初始请求,而不测试以后被重写的请求。

不需要<IfModule>包装器,除非您的站点打算在没有mod_rewrite的情况下运行。

请注意,像/web/index.php/page/这样的请求将导致两次重定向。首先到/index.php/page,然后到/page。由于这是一种极端情况,因此我认为双重重定向是可以接受的。

更新:我已经删除了上面的“目录”检查,因为这会阻止文档根目录(example.com/)被重写为/web子目录。如果您在站点的文档根目录中没有目录索引文档(例如index.php),则结果将为403。 (不过,对example.com/page/的请求应该仍然可以正常工作。)

使用302(临时)重定向进行测试,只有在确定其工作正常时才更改为301(永久),以避免浏览器中出现任何缓存问题。在测试之前,请确保清除浏览器缓存。