如何强制用于路由的.htaccess不路由.css,.js,.jpg等文件


How to force .htaccess used for routing to not route .css, .js, .jpg, etc. files?

我在一个站点的子目录中有以下。htaccess文件,它允许我将所有url路由到index.php,在那里我可以解析它们。

然而,它不允许标准文件,我需要的网站,如css, javascript, png等。

我需要改变什么(我假设在第四行)来允许这些文件,使它们不被路由到index.php?

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index'.php|public|css|js|png|jpg|gif|robots'.txt)
RewriteRule ^(.*)$ index.php/params=$1 [L,QSA]
ErrorDocument 404 /index.php

我注意到了。你用的是正斜杠而不是问号…参数重定向通常是这样的:

RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]

这应该自己工作,因为任何这些文件*应该*是真正的文件。

ErrorDocument 404 /index.php    
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]

要让站点忽略特定的扩展名,您可以添加一个条件来忽略大小写,只检查请求中文件名的末尾:

RewriteEngine On
RewriteCond %{REQUEST_URI} !('.css|'.js|'.png|'.jpg|'.gif|robots'.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]

如果你想忽略一个文件夹,你可以添加:

RewriteEngine On
RewriteCond %{REQUEST_URI} !(public|css)
RewriteCond %{REQUEST_URI} !('.css|'.js|'.png|'.jpg|'.gif|robots'.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]

最简单的方法是在规则的早期显式地忽略它们:

RewriteRule '.(css|js|png|jpg|gif)$ - [L]
RewriteRule ^(index'.php|robots'.txt)$ - [L]

这就避免了用RewriteCond到处携带它们。

根据您的选择,在执行此操作之前检查文件是否存在:

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule '.(css|js|png|jpg|gif)$ - [L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(index'.php|robots'.txt)$ - [L]

(注意文件检查会产生额外的磁盘访问)

您的想法是正确的,调整了第四行。^表示各种匹配字符串必须在行首。如果您不关心这些文件中的任何一个出现在文件中的位置,您可以删除^。这将避免重写*.css, *.js等;但也不会重写publicideas.html。

如果你想限制后缀,试试这个:

RewriteCond $1 !^(index'.php|public|.*'.css|.*'.js|.*'.png|.*'.jpg|.*'.gif|robots'.txt)$

表示匹配开头的任何内容,然后是.,然后是后缀。$表示在末尾匹配这些(后面没有任何内容)。

我不确定public,所以我离开了它(这意味着完全公开,没有别的-可能不是你的意思,但你可以在之前或之后添加*,或两者)。

RewriteCond %{REQUEST_FILENAME} !-f就足够了。

另一个选项是从重写中排除特定的文件。从TYPO3包:

# Stop rewrite processing, if we are in the typo3/ directory.
# For httpd.conf, use this line instead of the next one:
# RewriteRule ^/TYPO3root/(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon'.ico) - [L]
RewriteRule ^(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon'.ico) - [L]

该规则应该在实际重写之前出现。应该是

RewriteRule ^(public/|*'.css|*'.js|*'.png|*'.jpg|*'.gif|robots'.txt) - [L]