【问题标题】:Forcing directory slashes on virtual directories with htaccess使用 htaccess 在虚拟目录上强制目录斜杠
【发布时间】:2012-11-18 09:50:16
【问题描述】:

我了解如何在实际目录中添加目录斜杠,但我需要在虚拟目录中添加尾部斜杠 - 这样,当用户访问 example.com/website/blog/entries 时( 其中 /blog 和 /entries 都是虚拟目录),URL 地址将物理更改为:example.com/website/blog/entries/

这是我当前工作的 htaccess 代码,用于将假/虚拟目录转换为我的 php 脚本的参数:

RewriteRule ^/?([a-zA-Z_\-/.]+)$ index.php?file=$1 [L,QSA]  

这个 RewriteRule 使 example.com/website/blog/entries/ 看起来像 example.com/website/index.php?file=blog/entries / 仅适用于 PHP,而不适用于用户。

以下是一些我尝试过但无济于事的重写规则:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}$1/ [L,R=301]

# -----------------------------------------------

RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^.+/$ %1 [R=301,L]

我认为问题是因为我当前将虚拟目录转换为参数的正则表达式会查找以“/”开头的目录名称,因此当站点安装时不在根文件夹(“/”)中,或者如果存在不是尾部斜杠,它重定向到完全错误的东西。我无法在我的 htaccess 文件中的任何位置写入文件夹路径,因为路径会不断变化。例如,我不能使用类似的东西:

RewriteRule ^(.*)$ http://localhost:8888/project/$1/ [L,R=301]

有没有办法在将虚拟目录转换为 PHP 参数之前,在真实目录和虚拟目录上强制使用斜杠?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite rewrite


    【解决方案1】:

    以下内容应该可以满足您的需要:

    RewriteEngine On
    
    # Put here the URL where .htaccess is located
    RewriteBase /project/
    
    # Redirect virtual URLs w/o trailing slash to URL with it
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*[^/])$ $1/ [R=301,QSA,L]
    
    # pass virtual URLs into index.php as file argument
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^/?([a-zA-Z_\-/.]+)$ index.php?file=$1 [L,QSA]
    

    规则按照它们在配置中出现的顺序进行处理,因此重定向是在将数据传递到 index.php 之前完成的

    这是不使用RewriteBase 的版本,带有硬编码的 URL 部分:

    RewriteEngine On
    
    # Redirect virtual URLs w/o trailing slash to URL with it
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(.*[^/])$
    RewriteRule .* %1/ [R=301,QSA,L]
    
    # pass virtual URLs into index.php as file argument
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^/?([a-zA-Z_\-/.]+)$
    RewriteRule .* index.php?file=%1 [L,QSA]
    

    【讨论】:

    • 这几乎是完美的,并且回答了我的问题,除了我必须避免使用静态目录名称。您知道通过请求获取 .htaccess 文件所在目录的方法吗?像 %{REQUEST_DIR} 这样的东西,可以在我不写“/project/”的情况下获取目录的名称?谢谢你的回答!
    • @deraad 查看更新后的答案。即使没有硬编码/project/,也应该可以按预期工作
    • 我尝试在没有硬编码“/project/”名称的情况下使用它,但它不起作用,因为它重定向到错误的位置。相反,我编写了一个 PHP 脚本来重新创建 htaccess 文件,并使用它安装的站点的子目录的名称。
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2014-03-29
    • 2016-08-24
    • 2011-07-28
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多