【问题标题】:.htaccess - Rewrite all other php files to index.php [duplicate].htaccess - 将所有其他 php 文件重写为 index.php [重复]
【发布时间】:2016-06-24 15:50:37
【问题描述】:

这是我目前拥有的 htaccess 文件...

setEnv HTTP_TARGET_PAGE %{REQUEST_FILENAME}
ErrorDocument 404 default
ErrorDocument 301 default
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

#the below line doesn't work
RewriteCond %{REQUEST_URI} *.php
#the above line doesn't work

RewriteRule ^.*$ ./index.php

我试图让每个 php 文件或不存在的文件请求管道通过 index.php 进行处理。所有其他 php 文件有时都包含在 index.php 中(使用网址)。

所以我的 index.php 中可能有某个地方

if($my_url = "www.example.com/potato"){
    require_once("potato.php");
}

但我不希望他们输入“http://www.example.com/potato.php”并直接获取 php,而不需要标题等。我的 htaccess 不能正常工作(那一行每次都会出错)。但我不想重写所有内容,因为图像文件将无法正常工作。我该如何解决?

【问题讨论】:

  • 致 Popnoodles、3dgoo、Milap、Alex Tartan 和不走运的......不同的问题有不同的解决方案。您链接到的解决方案会重写所有内容。我只是试图重写 .php 请求和未找到的文件,您链接到的文件几乎会重写所有内容。

标签: php apache .htaccess mod-rewrite


【解决方案1】:

不太确定我是否理解您的要求,但我认为这就是您想要的。

RewriteEngine on

#don't do anything if index.php is called directly
RewriteRule ^index\.php - [L]
#if other php file called(user typed it in), redirect to extensionless uri
RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.php
RewriteRule ^ /%1? [R=302,L]    
#if extensionless uri maps to a real php file, forward to index.php
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [OR]
#or if not a real file or directory forward to index.php
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.+)/?$ /index.php [L,NC]

【讨论】:

  • 效果很好,谢谢!我在那里看到了几行我不明白的内容(例如 ^ /%1?[R=302,L]),我更喜欢理解我的代码(我一直在尝试理解 htaccess 和 mod_rewrite一会儿)。您有什么建议的资源吗?
  • @liljoshu 当您在条件/(.+)\.php 中使用组匹配时,后向引用变为%1,由(.+) 捕获,因此重写规则将使用302 重定向到该位置。一开始可能很难理解,只是需要时间。老实说,整个rewrite doc 是一个很好的起点。然后熟悉正则表达式,它就会走到一起。
猜你喜欢
  • 1970-01-01
  • 2018-04-03
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 2014-05-22
  • 2012-08-21
相关资源
最近更新 更多