代码之家  ›  专栏  ›  技术社区  ›  Andrew

在Apache1.3中将子目录作为根目录与htaccess一起使用

  •  26
  • Andrew  · 技术社区  · 15 年前

    我正在尝试部署一个由jekyll生成的站点,并希望将该站点保存在服务器上自己的子文件夹中,以使所有内容更具组织性。

    实际上,我想使用 /jekyll 作为根目录,除非实际的web根目录中存在类似名称的文件。所以有点像 /jekyll/sample-page/ 会显示为 http://www.example.com/sample-page/ ,而 /other-folder/ 将显示为 http://www.example.com/other-folder .

    我的测试服务器运行apache 2.2和以下 .htaccess (改编自 http://gist.github.com/97822 )完美无瑕:

    RewriteEngine On
    
    # Map http://www.example.com to /jekyll.
    RewriteRule ^$ /jekyll/ [L]
    
    # Map http://www.example.com/x to /jekyll/x unless there is a x in the web root.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/jekyll/
    RewriteRule ^(.*)$ /jekyll/$1
    
    # Add trailing slash to directories without them so DirectoryIndex works.
    # This does not expose the internal URL.
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_FILENAME} !/$
    RewriteRule ^(.*)$ $1/
    
    # Disable auto-adding slashes to directories without them, since this happens
    # after mod_rewrite and exposes the rewritten internal URL, e.g. turning
    # http://www.example.com/about into http://www.example.com/jekyll/about.
    DirectorySlash off
    

    但是,我的生产服务器运行apache 1.3,这不允许 DirectorySlash . 如果我禁用它,服务器会因为内部重定向过载而给出500个错误。

    如果我注释掉重写条件和规则的最后一部分:

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_FILENAME} !/$
    RewriteRule ^(.*)$ $1/
    

    基本上一切正常: http://www.example.com/sample-page/ 显示正确的内容。但是,如果省略了尾随斜杠,地址栏中的url将显示真正的内部url结构: http://www.example.com/jekyll/sample-page/

    在Apache1.3中,考虑目录斜杠的最佳方法是什么,其中有用的工具包括 斜线 不存在?我如何使用 /jekyll/ 目录作为站点根目录而不显示实际的url结构?

    编辑:

    在对Apache1.3进行了大量的研究之后,我发现这个问题实际上是在 Apache 1.3 URL Rewriting Guide

    我有一个(部分)已移动的documentroot,理论上它可以通过以下方式处理:

    RewriteRule   ^/$  /e/www/  [R]
    

    我还有一个臭名昭著的“拖尾斜杠问题”,通过设置 RewriteBase (如以下答复之一所建议的那样):

    RewriteBase    /~quux/
    RewriteRule    ^foo$  foo/  [R]
    

    问题在于两者的结合。移动文档根目录不会(不能?)使用 改写库 修复尾部斜线需要(?)它的HMM

    2 回复  |  直到 15 年前
        1
  •  57
  •   Andrew    15 年前

    经过一周的努力终于得到了它。重写规则真的是巫术

    RewriteEngine On
    
    # Map http://www.example.com to /jekyll.
    RewriteRule ^$ /jekyll/ [L]
    
    # Map http://www.example.com/x to /jekyll/x unless there is a x in the web root.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/jekyll/
    RewriteRule ^(.*)$ /jekyll/$1
    
    # Add trailing slash to directories within jekyll
    # This does not expose the internal URL.
    RewriteCond %{SCRIPT_FILENAME} -d
    RewriteRule ^jekyll/(.*[^/])$ http://www.example.com/$1/ [R=301]
    

    不需要 DirectorySlash . 它神奇地全部工作。

        2
  •  12
  •   Marcos Placona    15 年前

    您只需使用:

    RewriteBase   /jekyll
    

    一切都从这一点开始。