我们可以使用 .htaccess 文件重写 url。但在 .htaccess 文件中写入内容之前,我们需要验证我们使用的是哪种服务器。在这种情况下,您可以使用 apache 服务器或 Nginx 服务器。您只需添加一个
即可轻松检查
<?php phpinfo(); ?>
在一个 php 页面中。
案例 1:Apache 服务器:
确保在 apache 服务器中启用了 mod_rewrite 模块。这可以通过检查 phpinfo 包含的页面来识别。
url重写常用方法如下
重写引擎
这对于任何 apache 服务器都是必需的。这用于启用重写引擎。在某些情况下,它应该是默认开启的。因此,请确保在您的 htaccess 文件顶部必须强制执行以下代码
RewriteEngine On
重写规则
在某些情况下,您可能只有几个页面,您可以在 .htaccess 文件中指定网站中的每个页面。在这种情况下,您可以使用这些重写
例如
重写规则 ^article/used/to/be/here.php$ /article/now/lives/here/ [R=301,L]
假设你必须像这样重写 url
http://en.wikipedia.org/wiki/url_rewriting
你应该在你的 .htaccess 文件上写一些类似的东西
RewriteEngine On
RewriteRule ^wiki/(.+)$ w/index.php?title=$1 [L]
但是页面的实际实现会是这样的
http://en.wikipedia.org/w/index.php?title=url_rewriting
RewriteCond
这可用于针对某些条件重写某些 url。假设您需要使用您的网站名称添加或删除 www,并在某些情况下重定向到某个页面,例如“url 不可用或错误消息”
例子:
RewriteCond %{HTTP_REFERER} !^http://(www.)?example.com/.*$ [NC]
您可以进一步参考这里
Introduction to url rewriting
Rewrite with examples
案例2:nginx服务器
在你的 nginx 服务器上启用模块 HttpRewriteModule
根据 nginx 设置使用 location 重写你的 url
例子
location / {
root /path/to/drupal;
index index.php index.html;
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^/(.*)$ /index.php?q=$1;
}