如何在 .htaccess 中编写此 404 规则

发布于 2024-12-08 02:46:33 字数 341 浏览 1 评论 0原文

我有一个定制的 CMS。除了一件事之外,它工作得很好。我想知道如何最好地实现 404 功能。该网站应该只具有以下 url 类型

index.php?upn=something

,或者

gallery.php?groupId=2

在 index.php 或 gallery.php 之后附加到 url 的任何目录都应该抛出 404。另外,如果指定 upn 时在数据库中找不到内容,我想抛出 404。我意识到我可以将标头放入 php.ini 中。但我说过我会尝试从整体上更深入地了解这个问题。因此,如果您有任何信息或指示,我将不胜感激。

I have a custom CMS. It works very well except for one thing. I am wondering how best to implement 404 functionality. The site should only have the following url types

index.php?upn=something

or

gallery.php?groupId=2

Any directories that are appended to the url after index.php or gallery.php should throw 404's. Also I would like to throw a 404 if the content is not found in the database when a upn is specified. I realise that I can throw the header in php. But I said I would try to get a little more insight into this problem overall. So if ye have any info or pointers I'd appreciate them.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲念泪 2024-12-15 02:46:33

我喜欢通过我的 PHP 代码以编程方式执行此操作。您可以编写一些简单的路线组件,尝试找到您想要的内容。今天您只路由到操作(index.php?upn=gallery.php?groupId=),但将来有一天您可能会添加新的操作,并且您应该改变你的.htaccess,这更困难。如果您在应用程序层中完成所有操作,则可以更简单地更改它。

将此代码粘贴到项目根目录下的 .htaccess 文件中,并将每个请求路由到 router.php。一旦收到请求,您就可以决定采取什么行动。

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ router.php?url=$1 [QSA,L]
</IfModule>

希望有帮助。

I like to do this programatically from my PHP code. You could write some simple Route Component, that try to find what you want. Today you're routing just to actions (index.php?upn= and gallery.php?groupId=) but someday in the future you may add new one, and you should change your .htaccess, which is more difficult. If you do it all in your app tier you can change it simpler.

Paste this code in a .htaccess file at the root of your project, and will route every request to router.php. Once you have the request you can decide what action to do.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ router.php?url=$1 [QSA,L]
</IfModule>

Hope it helps.

孤千羽 2024-12-15 02:46:33

您必须在 php 代码中返回 404,但您可以在 htaccess 中设置 404 处理程序,如下所示:

ErrorDocument 404 /errors/notfound.html

You'd have to return the 404 in the php code, but you can set the 404 handler like so in htaccess:

ErrorDocument 404 /errors/notfound.html
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文