【问题标题】:htaccess directories, files and variableshtaccess 目录、文件和变量
【发布时间】:2011-10-19 01:47:54
【问题描述】:

我正在尝试获取类似于 $_SERVER["PATH_INFO"] 的内容,但奇怪的服务器问题阻止了我使用它...

在我的应用程序中,链接看起来像

www.domain.com/folder/file/variable
www.domain.com/folder/file
www.domain.com/file/variable or
www.domain.com/file/

使用 .htaccess,我试图访问正确的页面,而不是重定向到 index.php 或类似的页面。

到目前为止,我有这个,但它不起作用:)

RewriteRule ^(.+)$ /$1.php # page only
RewriteRule ^(.+)/(.+)$ /$1.php?x=$2 # page + variable
RewriteRule ^(.+)/(.+)$ /$1/$2.php # folder / page 
RewriteRule ^(.+)/(.+)/(.+)$ /$1/$2.php?x=$3 # folder / page + variable

我确定我需要使用 RewriteCond %{REQUEST_FILENAME} -f 来检查请求是文件名还是目录...但我无法使其工作...

变量可以包含所有奇怪的字符 - 这就是我与点匹配的原因...也许我应该尝试仅使用 az 匹配文件/文件夹名称(因为我认为它们不会包含除 az、_ 或- )。

非常感谢任何帮助,因为现在已经痛苦了将近两天了 :)

【问题讨论】:

  • 1) 由于您使用的模式首先以较长的模式开头,因为^(.+)$ 将匹配/file/ 以及/file/variable 以及/folder/file/variable; 2) 使用([^/]+) 而不是^(.+)$——这将帮助你#1

标签: file .htaccess variables directory


【解决方案1】:

将最具体的重写规则反转为第一个。

RewriteEngine On
RewriteRule ^(.+)/(.+)/(.+)$ /$1/$2.php?x=$3 [L]

# RewriteRule to check that the file is exists here
RewriteCond %{REQUEST_URI} ^(.+)/(.+)$
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI}.php -f
RewriteRule ^(.+)/(.+)$ /$1/$2.php [L]

# If file is not exists, then check by put to the variable
RewriteRule ^(.+)/(.+)$ /$1.php?x=$2 [L]
RewriteRule ^(.+)$ /$1.php [L]

【讨论】:

  • 是的,是的,抱歉没有详细说明,一切都在那里,RewriteEngine On 等......我的 htaccess 配置基本上可以工作,但当时只适用于一种情况。如果我只评论一行,然后点击相应的 URL,它就可以了。
【解决方案2】:

大多数人/框架将没有指定扩展名的所有内容传递给单个 php 前端控制器,然后由该控制器确定要做什么。我认为大多数人走这条路的一个原因是 mod_rewrite 的复杂程度!

【讨论】:

    【解决方案3】:

    感谢@LazyOne 的提示,我能够解决这个问题。

    htaccess 文件现在看起来像这样:

    RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)$ /$1/$2.php?x=$3
    RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)/$ /$1/$2.php
    RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)$ /$1.php?x=$2
    RewriteRule ^([-a-zA-Z0-9_]+)/$ /$1.php
    

    所有文件夹或文件路径必须以“/”结尾,而变量不得。这在我的框架中不是问题 - 但可能对其他人没有用。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      相关资源
      最近更新 更多