如果通过别名目录访问网站,则URL重写不起作用

时间:2012-02-13 01:10:08

标签: apache mod-rewrite wampserver

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

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

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

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

当我尝试访问http://localhost/mysite/articles/1时,我收到了此回复:

  

未找到

     

在此未找到请求的网址/www/mysite/article.php   服务器

我可以确认article.php处有d:\www\mysite\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>

1 个答案:

答案 0 :(得分:7)

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

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

由于您的/mysite/

,RewriteBase必须为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