ChatGPT体验 AI绘画体验
nginx通过url重写实现伪静态示例
提问人:ppw_crxis 时间:2023-04-20 公开状态:

提问人:ppw_crxis 时间:2023-04-20 公开状态:


假设我们有一个网站,网站首页为/index.php,我们想通过URL重写来实现伪静态,将/index.php转换为/index.html。
首先,需要在nginx的配置文件中启用URL重写模块,方法如下:
打开nginx的配置文件nginx.conf,在http块下添加一行:
```
http {
...
location / {
...
# 开启URL重写
rewrite ^(.*)$ /index.php?$query_string;
}
}
```
其中,`rewrite ^(.*)$ /index.php?$query_string;`表示将所有请求都重写到index.php文件中。
接下来,我们需要添加一个新的location块来处理重写后的URL:
```
http {
...
location / {
...
# 开启URL重写
rewrite ^(.*)$ /index.php?$query_string;
# 处理重写后的URL
location ~ ^/(.*)\.html$ {
try_files $uri /index.php?$query_string;
}
}
}
```
其中,`location ~ ^/(.*)\.html$`表示匹配所有以.html结尾的URL。
`$uri`表示当前请求的URI。
`try_files $uri /index.php?$query_string`表示尝试请求当前URI对应的文件,如果找不到,则将请求重定向到/index.php文件中,并将请求参数通过$query_string传递给index.php。
保存配置文件后,重启nginx服务生效。现在,当访问http://example.com/时,将自动重写到/index.php文件中,而访问http://example.com/index.html时,将被重写到/index.php文件中,并且URL中的.html会被去掉。