【问题标题】:Regarding HTaccess and sub directory关于HTaccess和子目录
【发布时间】:2015-11-23 12:22:31
【问题描述】:

我有一个关于 htaccess 的问题要问

我有这个结构

book
-> read.php
-> avatar
  --> 1
    --> index.html

所以在过去,我使用 read.php 来提供我的内容

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ read.php?id=$1&num=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ read.php?id=$1&num=$2&page=$3 [L]

但是现在,我有了自己的文件夹结构和预生成的 html,所以它们驻留在

avatar/1/index.html

但是当我输入例如

avatar/1/2 这是一个不存在的文件夹和文件,我想使用我的 read.php 而不是它尝试访问返回 403 的文件和文件夹。

如果文件夹不包含 index.html,我如何更改我的 htaccess 代码以使用 read.php 及其查询字符串

谢谢

例如,如果我输入

/book/avatar/2

由于没有 /book/avatar/2/index.html (目前它给我扔了 403 禁止)

它应该使用 htaccess

book/read.php?id=$1&num=$2&page=$3

-- 更新 htaccess

RewriteEngine on
RewriteBase /book

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d


RewriteRule ^([^/]+)/(\d+)/([^/]+)$ read.php?id=$1&num=$2&page=$3 [L,QSA]
RewriteRule ^([^/]+)/(\d+)/?$ read.php?id=$1&num=$2 [L,QSA]
RewriteRule ^([^/]+)/?$ chapter.php?id=$1 [L,QSA]

如果我输入

example.com/book/avatar/2/1

它仍然加载 chapter.php?id=1

如果我输入

example.com/book/avatar

它还加载 chapter.php?id=1

如果我在 RewriteCond 之后输入这个

RewriteRule ^ - [L]

所有文件都会出现404错误

【问题讨论】:

  • 请检查权限,因为“403”意味着一些 acl 或限制,htaccess 对我来说似乎不错。

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

/book/.htaccess 中,您可以创建此规则:

RewriteEngine On
RewriteBase /book/

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/(\d+)/([^/]+)$ read.php?id=$1&num=$2&page=$3 [L,QSA]

RewriteRule ^([^/]+)/(\d+)/?$ read.php?id=$1&num=$2 [L,QSA]

RewriteRule ^([^/]+)/?$ chapter.php?id=$1 [L,QSA]

仅当请求不是文件或目录时,这将处理 /book/avatar/2/book/avatar

【讨论】:

  • 我认为它应该更通用,“头像”可以改变我的想法。也请
  • 我可以在 /book 而不是 /avatar/.htaccess 中添加这个 htaccess
  • @anubhava ,上面的代码解决了 read.php 的问题。但是有一个问题是如果我去 /book/avatar ,如果 /book/avatar 不包含 index.html ,它应该使用 read.php?id=$1 ,我如何让它从你的 htacccess 工作
  • @anubhava 我试过代码给我一个 404 未找到。但是当我删除 RewriteRule ^ - [L] 时,我键入 /book/avatar/1 ,它实际上使用单个查询字符串 ?id=$1 加载规则
  • RewriteRule ^ - [L] 似乎有问题。删除它后,我不再有 404 错误,但即使我有 2 个查询字符串,它也会使用 ?id=1 的重写规则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
相关资源
最近更新 更多