.htaccess:如果文件不存在,则重定向';不存在

.htaccess:如果文件不存在,则重定向';不存在,.htaccess,redirect,yii2,.htaccess,Redirect,Yii2,这是一个相当普遍的问题,但在我的案例中有一些区别,这使得这一切更加困难 Apache2 web服务器,启用prettyUrl的Yii2框架 以下是Yii2提供的初始.htaccess文件: RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise f

这是一个相当普遍的问题,但在我的案例中有一些区别,这使得这一切更加困难

Apache2 web服务器,启用prettyUrl的Yii2框架

以下是Yii2提供的初始
.htaccess
文件:

RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php
/docs
web目录。如果文件存在,我想从中获取文件,如果文件不存在,则重定向到
/docs generator/create?file=

因此,我添加了一条规则:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/docs
RewriteRule ^docs/([\w-_.]+) http://kz_proj.test/docs-generator/create?file=$1 [L]

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php
它的工作,但相当奇怪。。。首先,我不能从
http://kz_proj.test/docs-generator/create?file=$1
。没有全名是不行的。第二个是关于
^/docs
^docs/([\w-.]+)
的,没有前导字符。为什么这些规则的第一部分在我的案例中不一样

我猜规则有问题

您可以使用:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^docs/([\w-_.]+) /docs-generator/create?file=$1 [L,R=301]

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule ^ index.php
它与域名一起工作,因为在这种情况下它必须是重定向,但不能没有重定向。我添加了
[R=301]
以强制重定向

无需添加
RewriteCond%{REQUEST_URI}^/docs

因为测试与重写规则^文档

为什么这些规则的第一部分在您的案例中不能相同?
请求\u URI
始终以
/

RewriteRule测试路径
永远不要在.htaccess中以
/
开头(为什么???)

为什么不使用404重定向???因为我在脚本中生成内容并将其传递给用户(文件是否存在)。太好了,它适合我!为了链接一些这样的规则,我应该添加新的
RewriteCond+RewriteRule
语句,或者只添加
RewriteRule
新的
测试路径
部分?很高兴知道它成功了。您需要添加
RewriteCond+RewriteRule
,因为
RewriteCond
只适用于下一个
RewriteRule
。或者,您可以使用
RewriteRule^-[L]