【问题标题】:Trying to create an htaccess file to handle both extensionless files and missing files尝试创建一个 htaccess 文件来处理无扩展名文件和丢失文件
【发布时间】:2016-04-28 17:46:36
【问题描述】:

我正在尝试结合两个 htaccess 重写规则:一个处理无扩展名链接,另一个将丢失的文件发送到索引页面以处理它们。我分别为它们提供了工作代码,但将两者结合起来很棘手。

规则是这样的:

  1. 如果 URI 是一个目录,请转到它并让其中的索引文件处理它。
  2. 如果 URI 有扩展名并且文件存在,则转到该文件。
  3. 如果 URI 没有扩展名,请添加 .php 并转到该文件(如果存在)。
  4. 对于任何不存在的文件(带或不带扩展名),将其发送到索引文件进行处理。

原因是我有一些静态页面和一些从数据库动态创建的。

仅供参考,“无扩展”代码是

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)/?$ $1.php [L]

并且“重定向到索引”代码是

RewriteEngine On
RewriteRule (.*) index.php [PT,QSA] 

【问题讨论】:

    标签: php apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    这样吧:

    DirectoryIndex index.php
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^.]+?)/?$ $1.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [L]
    

    【讨论】:

    • anubhava 和 Rijul 的代码都在我的测试中工作,所以感谢你们俩。我接受 anubhava 只是因为它是第一个,除非有更博学的人能指出更可取的解决方案。
    【解决方案2】:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.+)$ $1.php [L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.+)$ index.php?url=$1 [L]
    

    在情况 4 中,如果您必须处理对不存在的文件的请求(带或不带扩展名),您需要知道在 index.php 中请求的 url。为此添加了 GET url 参数,您可以在 php 文件中使用 $_GET['url']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      相关资源
      最近更新 更多