在单个子目录中设置自定义404错误(apache和.htaccess)

时间:2013-09-26 11:53:00

标签: regex wordpress apache .htaccess mod-rewrite

我有一个带有一些新闻的简单wordpress页面。在根目录中,我使用规则设置.htaccess:

RewriteBase /news/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]

正如您所看到的那样,如果客户端请求不存在的文件或目录,则会将其重定向到/news/index.php。

现在,我想设置一下,如果他从/ news / wp-content / uploads /子目录中调用不存在的图形文件,他应该得到一个自定义图形(让我们说/ news / wp-content / uploads / noimage .PNG)。为此,我修改了.htaccess:

RewriteBase /news/wp-content/upload/
RewriteCond %{REQUEST_FILENAME !-f
RewriteRule . /news/wp-content/upload/notFound.png

RewriteBase /news/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]

但是现在当我尝试加载页面(甚至索引页面)时,我收到内部服务器错误。这有什么不对?

2 个答案:

答案 0 :(得分:1)

你的第一条规则实际上是劫持了所有合法的WP请求,因为那些永远都不是有效的文件。用以下代码替换完整的代码:

如果wp-contnent目录中没有.htaccess:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /news/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(wp-content/uploads)/.+$ $1/notFound.png [L,NC]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

如果在wp-contnent目录中有.htaccess,则在wp-contnent/.htaccess文件的顶部使用此代码:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^uploads/.+$ /news/wp-content/uploads/notFound.png [L,NC]

答案 1 :(得分:0)

为什么不尝试这样做,而不是摆弄RewriteBase:

RewriteCond %{REQUEST_URI} ^/news/wp-content/upload/ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /news/wp-content/upload/notFound.png [L]