有什么方法可以用 .htaccess 简化我的 url 吗?

Is there any way to simplify my url with .htaccess?

我正在尝试使用 .htaccess RewriteRule 来简化我的 url,但我没有成功。

我希望这个 http://localhost/site/auth 中的 url 像这样 http://localhost/auth,我想从 url 中删除 site

到目前为止我尝试了什么

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite --- http://localhost/site/auth => http://localhost/auth
RewriteRule ^site/auth$ /auth?&%{QUERY_STRING}
</IfModule>

您需要反过来编写规则。您想在内部重写 传入的 请求,因此请求 http://localhost/auth ...

RewriteEngine On
Rewrite ^/?auth$ => /site/auth [END]

就这些了。

无需在此处测试现有文件或文件夹,因为您没有实施通用规则,而是实施了特定规则。并且不需要添加查询字符串,这是重写的默认设置。此外,我看不到 <IfModule ...> 括号的好处,因为如果没有该模块,您的逻辑将无法正常工作:

为此,需要将 apache http 服务器的重写模块加载到服务器中,并且需要为 http 主机“localhost”激活它,这很可能只是您的默认主机。

如果您还想添加外部重定向,可以这样做:

RewriteEngine On
RewriteRule ^/?site/auth$ /auth [R=301,END]
Rewrite ^/?auth$ => /site/auth [END]

您可能想先使用 R=302 临时重定向,然后在确定一切按预期工作后才将其更改为 R=301 永久重定向。这样你就可以防止缓存问题。


在您的 http 服务器的实际主机配置中实施此类规则是有意义的。如果您更喜欢使用分布式配置文件(“.htaccess”),例如,因为您计划稍后部署到一个您无法访问实际配置的廉价主机提供商,那么您需要确保对此类的解释该位置启用了文件(请参阅文档中的 AllowOverride 指令)。在这种情况下,您需要接受性能损失。