.htaccess 将具有特定路径的 URL 重定向到 404,并排除一些与异常路径相同的 URL

.htaccess redirect URLs with specific path to 404 and exclude some URLs with the same path as exception

我在 Codeigniter(3.1.11) 上有一个应用程序。基本上,我想要在 URI 中具有 dashboard 的 URL 的 404 重定向。喜欢这些:

dashboard/foo/bar
dashboard/foo-2/bar-2
dashboard/something
...

此外,我想在重定向规则中保留一些例外情况,因此,一些具有 dashboard 作为路径 URI 的特定 URL 应该从该重定向中排除。假设我想排除一些网址,例如:

dashboard/new-foo/new-bar
dashboard/one-thing/abc
dashboard/another-thing/xyz

我试了几次,但排除规则不起作用。它将所有 URL 重定向到 404。这就是我在 .htaccess 中的内容:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(dashboard/new-foo/new-bar) [NC]  # Exclude this url (this condition is not working)
RewriteRule ^(.*)$ dashboard/ [R=404,L]

RewriteEngine on
RewriteCond  !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/ [L,QSA]

我不是 htaccess 专家,但我很确定您需要 2 行 RewriteCond,其中一行包含所有仪表板 url,第二行排除新的。每个 RewriteCond 都隐含地与“AND”连接,因此如果您有许多不同的模式要排除并且您需要第三个 RewriteCode,那么您将需要在第二个条件下用“OR”连接第三个。

例如

RewriteCond %{REQUEST_URI} ^/dashboard/(.*) [NC]
RewriteCond %{REQUEST_URI} !^/dashboard/new-(.*) [NC]
RewriteRule ^(.*)$ 404-page/ [R=404,L]

还有几件事我想提一下:1) 你的 RewriteRule 重定向回 /dashboard URL 所以你可能会在这里连续查看。 2) 不需要开启Rewrite引擎两次,在顶部一次就够了。

如果 htaccess 中的重写规则变得复杂,那么也许您可以使用 index.php 文件来处理它(或 Codeigniter 中的其他方法)。

它可以在具有否定先行条​​件的单个规则中完成,如下所示:

RewriteEngine on

RewriteRule ^dashboard(?!/new-foo/new-bar|/one-thing/abc|/another-thing/xyz) - [R=404,NC,L]

RewriteCond  !^(index\.php|resources|robots\.txt) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/ [L]