【问题标题】:htaccess: relative paths not working properlyhtaccess:相对路径无法正常工作
【发布时间】:2017-06-29 21:42:24
【问题描述】:

首先,我想要实现的目标: 我在基础http://example.com/subdir 下进行测试,这是所有子文件夹、index.php 和 .htaccess 所在的位置。

我有 3 组规则,如 .htaccess 中所示(删除了额外的规则):

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on

# Convert   item/edit/xx -> index.php?p=edit&id=xx
# Convert   item/remove/xx -> index.php?p=remove&id=xx
#RewriteCond %{REQUEST_URI} ^/item [NC]
#RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]
RewriteRule ^item/([a-z]+)/([0-9]+)$    index.php?p=$1&id=$2 [NC,L]

# Convert category/yyyy -> customer/pagination.php?category=yyyy

#RewriteCond %{QUERY_STRING} category=([a-zA-Z\s]+)$
RewriteRule ^customer/category/([a-zA-Z\s]+)$     customer/pagination.php?category=$1  [NC,L]


# Convert action/about   -> index.php?p=about
# Convert action/terms   -> index.php?p=terms


#RewriteCond %{QUERY_STRING} p=([a-z]+)$
RewriteRule ^action/([a-z]+)$     index.php?p=$1  [NC,L]

</IfModule>

我遇到的第一个问题是 RewriteCond 无法正常工作(未找到路径),因此暂时将其注释掉。 RewriteRule 适用于绝对路径(例如 RewriteRule ^action/([az]+)$ http://example.com/subdir/index.php?p=$1 [NC,L]),但是这会导致浏览器显示真实的 URL,因此我试图让它与相对路径。 我的问题是,在第一次重定向后,左侧链接的第一部分被添加到路径中,即单击操作/关于链接后,http://example.com/subdir 变为http://example.com/subdir/action。 定义 RewriteBase 或在 URL 前添加斜杠只会让事情变得更糟。 我将感谢一位眼光敏锐的专家,他能找出我问题的根本原因。

【问题讨论】:

标签: php .htaccess mod-rewrite directory


【解决方案1】:

第一个问题是%{REQUEST_URI} 总是包含完整路径。因此,您的条件可以更改为:

RewriteCond %{REQUEST_URI} ^/subdir/item [NC]

第二个问题实际上并不能使用 .htaccess 解决。你只需要告诉浏览器你想要什么。因此,您可以使用两种方法之一。

  1. 使用&lt;base&gt; 元素(将应用于页面上的所有相对URI):

    <base href="/subdir" />
    
  2. 使用浏览器中显示的 URL 的相对路径:

    <a href="terms">Click here</a>
    

如果您真的想使用 .htaccess 来解决问题,唯一真正的方法是在请求重复目录后将其删除。

【讨论】:

  • 非常感谢,设置 有帮助,尽管我必须将 PHP 中的所有标头重定向更改为绝对路径才能使所有链接正常工作。我会在 #RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC] 工作后发布完整的代码。
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多