【问题标题】:URL rewriting doesn't work if web-site is accessed via alias directory如果通过别名目录访问网站,则 URL 重写不起作用
【发布时间】:2012-02-13 01:10:08
【问题描述】:

我在本地计算机上的目录d:\www\mysite 中有一个网站。我安装了 WAMPServer 并为我的站点设置了一个别名目录 mysite

例如,http://localhost/mysite/static-resource.html 正确检索了我位于 d:\www\mysite\static-resource.html 中的文件。

我的问题是我的 .htaccess 文件中的 URL 重写:

RewriteEngine On    
RewriteRule ^articles/(\d+) ./article.php?id=$1

当我尝试访问 http://localhost/mysite/articles/1 时,我收到了以下响应:

未找到

在此找不到请求的 URL /www/mysite/article.php 服务器。

我可以确认d:\www\mysite\article.php 存在一个article.php 文件。

过去,我将网站的根 (d:\www\mysite) 设置为 Apache 服务器的 DocumentRoot(而不是默认的 c:\wamp\www),在这种情况下,我的 URL 重写工作,所以我当前的问题必须与我的网站位于别名目录“后面”这一事实有关。


我的mysite.conf文件的内容:

Alias /mysite/ "d:/www/mysite/" 

<Directory "d:/www/mysite/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order allow,deny
    Allow from all
</Directory>

【问题讨论】:

  • 您能否确认为新的别名目录正确设置了AllowOverride
  • @clmarquart 我不确定什么是正确设置。我已经用相关信息更新了我的问题...

标签: apache mod-rewrite wampserver


【解决方案1】:

我在您的重写规则中没有看到 RewriteBase。
在您的 .htaccess 中,添加 RewriteBase 规则。

RewriteEngine On    
RewriteBase /mysite/
RewriteRule ^articles/(\d+) ./article.php?id=$1

RewriteBase 必须有 /mysite/ 因为你的 Alias /mysite/ "d:/www/mysite/"

如果只访问http://localhost/mysite,它应该返回一个not found on this server。 如果您不希望发生这种情况,请在上面添加另一个别名,如下所示:

Alias /mysite "d:/www/mysite/" 

就这个:

AliasMatch /mysite(/.*)? d:/www/mysite/$1 

为什么是 RewriteBase?来自RewriteBase Directive Apache Docs:

RewriteBase 指令显式设置每个目录重写的基本 URL。正如您将在下面看到的,RewriteRule 可以在每个目录的配置文件 (.htaccess) 中使用。在这种情况下,它将在本地进行操作,在处理之前剥离本地目录前缀,并将重写规则仅应用于其余部分。处理完成后,前缀会自动添加回路径。默认设置是; RewriteBase 物理目录路径

当新 URL 发生替换时,此模块必须将 URL 重新注入服务器处理。为了能够做到这一点,它需要知道相应的 URL 前缀或 URL 基是什么。默认情况下,此前缀是相应的文件路径本身。然而,对于大多数网站来说,URL 与物理文件名路径并不直接相关,因此这种假设通常是错误的!因此,您可以使用 RewriteBase 指令来指定正确的 URL 前缀。

来自RewriteBase Directive Apache Docs的示例:

#
#  /abc/def/.htaccess -- per-dir config file for directory /abc/def
#  Remember: /abc/def is the physical path of /xyz, i.e., the server
#            has a 'Alias /xyz /abc/def' directive e.g.
#

RewriteEngine On

#  let the server know that we were reached via /xyz and not
#  via the physical path prefix /abc/def
RewriteBase   /xyz

#  now the rewriting rules
RewriteRule   ^oldstuff\.html$  newstuff.html

【讨论】:

  • RewriteBase,我明白了。谢谢:)
  • 是否可以省略RewriteBase,或者设置为.htaccess所在目录?
  • 我在同样的场景下也有同样的问题,但添加RewriteBase /my-alias 对我没有用。有什么想法吗?
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 2021-03-02
  • 2013-12-23
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 2010-11-23
  • 2013-01-17
相关资源
最近更新 更多