.htaccess 如何检查 URI +在 RewriteRule 之前文件扩展名不存在

发布于 2025-01-04 07:18:58 字数 405 浏览 3 评论 0原文

当通过这样的 URL 访问页面时:

/pagename

如何通过 htaccess

/pagename.htm

检查以下文件是否存在,如果不存在则加载 index.php?

这就是我正在处理的内容:

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

我尝试过这种方法的变体,但没有运气: RewriteCond %{REQUEST_URI} !/.htm -f

When a page is accessed via an URL like this:

/pagename

How can we check if the following file exists via htaccess

/pagename.htm

And then load index.php if not?

Here's what I'm working with:

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

I've tried a variation of this but no luck:
RewriteCond %{REQUEST_URI} !/.htm -f

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

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

发布评论

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

评论(1

各自安好 2025-01-11 07:18:58
# If the URI is not .htm and doesn't have any additonal params, try .htm
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?![^/]+\.htm)([^/]+)$ $1.htm [L,R=302]
# Adding the R flag causes the URI to be rewritten in the browser rather than just internally

# If the URI is .htm but it doesn't exist, pass to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/\.]+\.htm)$ $1/no [L]

# Passes requested path as 'q' to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/no/?$ index.php?q=$1 [L]

应该对你来说相当优雅。如果找不到该文件,它只会将其传递给index.php。您当然可以修改它使用的变量,我只是将“q”用于通用目的。

另外,请注意,您可以将其压缩为一组 RewriteCond。我在这里出于注释目的对它们进行了扩展。

# If the URI is not .htm and doesn't have any additonal params, try .htm
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?![^/]+\.htm)([^/]+)$ $1.htm [L,R=302]
# Adding the R flag causes the URI to be rewritten in the browser rather than just internally

# If the URI is .htm but it doesn't exist, pass to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/\.]+\.htm)$ $1/no [L]

# Passes requested path as 'q' to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/no/?$ index.php?q=$1 [L]

Should work rather elegantly for you. If it can't find the file, it just passes it on to index.php. You can of course modify what variable it uses, I just used 'q' for generic purposes.

Also, do note that you can condense this down to a single set of RewriteConds. I've expanded them for annotation purposes here.

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