如何从 Perl 脚本传递自定义 404 错误?
我有一个 .htaccess 文件,如果满足某些条件,它会调用 perl 脚本。 htaccess 文件如下所示:
Options +FollowSymlinks
ErrorDocument 404 /404.shtml
#check existence
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{PATH_INFO} (.*)
#redirect for codes
RewriteCond %{REQUEST_URI} !\.[css|jpg|gif|png]
RewriteRule ^(.*) /cgi-bin/normalized\.pl?code=$1 [R=301]
代码被传递到 normalized.pl 文件,这样如果请求的 URL 是 www.domain.com/code1,则将传递“code1”。如果代码存在,我可以将用户引导至正确的页面。
但是,如果代码不存在,我希望将用户定向到 htaccess 文件中定义的自定义 404 页面。
但似乎发生的情况是 htaccess 文件将规范化的 pl 视为现有文件,并且我得到了 perl 脚本的 200 响应。然后,perl 脚本返回一个 404 标头(如下所示)但它不显示我的自定义 404 页面 - 只是一个浏览器标准页面。
print header(-status=>'404 Not Found',-type=>'text/html');
我怀疑这是因为 .htaccess 文件在 perl 脚本运行时已经被传递。
在这种情况下,如何说服浏览器显示自定义 404 页面?强制从 Perl 脚本进行 301 重定向到 404 页面是否明智/可接受?但这会对搜索引擎索引页面产生任何影响吗?
I have an .htaccess file which calls a perl script if certain conditions are met. The htaccess file looks like this:
Options +FollowSymlinks
ErrorDocument 404 /404.shtml
#check existence
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{PATH_INFO} (.*)
#redirect for codes
RewriteCond %{REQUEST_URI} !\.[css|jpg|gif|png]
RewriteRule ^(.*) /cgi-bin/normalized\.pl?code=$1 [R=301]
Codes get passed to the normalized.pl file such that if the URL requested was www.domain.com/code1, "code1" would be passed. If the code exists I can refer the user onwards to the correct page.
However, if the code doesn't exist I wish for the user to be directed to my custom 404 page as defined in the htaccess file.
What seems to happen though is that the htaccess file sees the normalized pl as an existing file and I get a 200 response for the perl script. The perl script then returns a 404 header (as shown below) but it doesn't show my custom 404 page - just a browser standard one.
print header(-status=>'404 Not Found',-type=>'text/html');
I suspect it's because the .htaccess file has already been passed by the time the perl script runs.
How can I convince my browser to display the custom 404 page in this case? Would it be advisable/acceptable to force a 301 redirect from the perl script to the 404 page? But would that have any impact on search engines indexing the pages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Perl 脚本发送的 404 标头仅告诉浏览器未找到该页面。它无法将这一信息告诉 Web 服务器,因为 Web 服务器由于找到了您的 Perl 脚本而认为请求成功。
此时发送自定义 404 页面的唯一方法是让 Perl 脚本在 404 标头之后
打印
该页面的 HTML。The 404 header sent by your Perl script only tells the browser that the page was not found. There is no way for it to tell that to the web server, since the web server considers the request to be successful due to the fact that it found your Perl script.
The only way for you to send your custom 404 page at that point would be to have the Perl script
print
the HTML for it after the 404 header.