nginx伪静态规则
封面图
•
2026-01-03
•
NGINX
255
0
0
0
Nginx 本身不支持传统的 `.htaccess` 文件(如 Apache 所使用的),但可以通过配置 `nginx.conf` 或站点配置文件来实现伪静态(URL 重写)功能。伪静态通常用于将动态 URL 转换为更友好的、SEO 友好的静态 URL。 以下是一些常见的 Nginx 伪静态规则示例,适用于不同的场景: --- ## ✅ 1. 基本的伪静态规则(例如:`/index.php?id=123` → `/index/123.html`) ```nginx location / { if ($request_filename !-f) { rewrite ^/(.*)$ /index.php?$1 last; } } ``` 这个规则的意思是:如果请求的文件不存在,则将请求重写到 `index.php` 并传递原始路径作为参数。 --- ## ✅ 2. 更复杂的伪静态规则(例如:`/news/123.html` → `/news.php?id=123`) ```nginx location / { try_files $uri $uri/ /news.php?id=$1; } # 如果使用正则匹配 rewrite ^/news/([0-9]+)\.html$ /news.php?id=$1 last; ``` --- ## ✅ 3. WordPress 伪静态规则 WordPress 的伪静态规则通常如下: ```nginx location / { try_files $uri $uri/ /index.php?$args; } ``` 这会将所有请求尝试匹配真实文件或目录,否则转发给 `index.php` 处理。 --- ## ✅ 4. ThinkPHP 伪静态规则(基于 URL 重写) ```nginx location / { if (!-e $request_filename) { rewrite ^(.*)$ /index.php/$1 last; } } ``` --- ## ✅ 5. 使用 `rewrite` 模块进行 URL 重写(例如:`/user/123` → `/user.php?id=123`) ```nginx rewrite ^/user/([0-9]+)$ /user.php?id=$1 last; ``` --- ## ✅ 6. 防止直接访问 PHP 文件(可选) ```nginx location ~ \.php$ { deny all; } ``` --- ## 📌 注意事项: - **`try_files`** 是推荐的方式,它比 `if` 判断更高效。 - 确保你的 Nginx 配置中启用了 `rewrite` 模块(一般默认已启用)。 - 修改完配置后,记得测试并重新加载 Nginx: ```bash nginx -t systemctl reload nginx ``` --- ## 🔍 示例:完整的 Nginx 配置片段 ```nginx server { listen 80; server_name example.com; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php-fpm.sock; } # 伪静态规则 rewrite ^/news/([0-9]+)\.html$ /news.php?id=$1 last; } ``` --- 如果你有具体的伪静态需求(比如某个 CMS 或框架的规则),可以告诉我,我可以帮你定制规则。
上一篇:
邮件系统的组成部分介绍
下一篇:
nginx(虚拟主机配置、ip、域名、端口号)
标题录入,一次不能超过6条
留言
评论