返回首页

Nginx 的 mod_rewrite:CMS 中的 .htaccess

nginx-mod-rewrite 模块在 Nginx 中模拟 Apache .htaccess,用于 CMS。支持 mod_rewrite 规则、回退到 index.php 和缓存。基准测试显示性能接近原生 Nginx。为 RHEL/Debian 提供构建和配置示例。

Nginx + .htaccess:CMS 的 mod_rewrite 模块
Advertisement 728x90

Nginx mod_rewrite 模块:为 CMS 提供 .htaccess 支持

Nginx 不支持 Apache 的 .htaccess,这在将网站迁移到 WordPress、Drupal 或 Grav 等流行 CMS 平台时带来了挑战。这些系统依赖 mod_rewrite 来实现 SEO 友好的 URL、目录保护和错误处理。没有 .htaccess,CMS 要么返回 404 错误,要么需要 Nginx + Apache 组合设置,增加了额外开销。

一个名为 nginx-mod-rewrite 的模块被开发出来,用于模拟 mod_rewrite。它动态解析 .htaccess,应用重写规则,包括内部重定向和回退到 index.php。该模块在服务器、位置和 .htaccess 级别运行,通过请求池缓存最小化文件读取。

控制面板中的解决方案

像 HestiaCP 这样的控制面板通过两种方式解决此问题:

Google AdInline article slot
  • try_files $uri $uri/ index.php?$args — 覆盖 50–80% 的情况,但并非所有 mod_rewrite 规则。
  • ngx_http_rewrite_module 模板 — 针对特定 CMS 的完整 .htaccess 等效方案,但将配置紧密绑定到平台。

nginx-mod-rewrite 模块消除了这些限制:它支持 RewriteMap(最小化)、RewriteOptions,无需模板,并允许在没有服务器管理员权限的情况下编辑 .htaccess。

构建和安装模块

可以在主机或 Docker 中构建。对于 Almalinux 9:

  • 安装 Docker。
  • 克隆仓库。
  • 运行 bash package_preparer.sh prepare "almalinux:9"

结果是在 tmpbuild/ 中的 RPM 包:

Google AdInline article slot
tmpbuild/nginx-mod-rewrite-0.1-1.el9.src.rpm
tmpbuild/nginx-mod-rewrite-0.1-1.el9.x86_64.rpm
tmpbuild/nginx-mod-rewrite-debuginfo-0.1-1.el9.x86_64.rpm
tmpbuild/nginx-mod-rewrite-debugsource-0.1-1.el9.x86_64.rpm

类似地,对于 Debian — DEB 包。

服务器配置

CMS 站点的服务器块示例:

server {
	listen      127.0.0.1:80;
	server_name test.my.brp www.test.my.brp;
	root        /home/test/web/test.my.brp/public_html;
	index       index.php index.html index.htm;

	HtaccessEnable on;

	location ~ /\.(?!well-known\/) {
		deny all;
		return 404;
	}

	location ~* ^.+\.(jpeg|jpg|png|webp|gif|bmp|ico|svg|css|js|txt)$ {
		expires max;
		fastcgi_hide_header "Set-Cookie";
	}

	location / {
		RewriteEngine On;

		location ~ [^/]\.php(/|$) {
			try_files $uri =404;

			include /etc/nginx/fastcgi_params;

			fastcgi_index index.php;
			fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

			fastcgi_pass unix:/run/php74-fpm.sock;
		}
	}
}

HtaccessEnable on 激活 .htaccess 解析。静态文件被排除在重写处理之外以提高性能。

Google AdInline article slot

性能基准测试

在 Drupal 上的测试(wrk,30 秒):

| 场景 | Nginx + php-fpm | Nginx + mod_rewrite | Nginx + Apache + php-fpm |

|---------------------------|-----------------|--------------------|---------------------------|

| /(回退到 index.php) | 129.74 请求/秒 | 125.94 请求/秒 | 121.31 请求/秒 |

| /robots.txt(静态) | 7384.25 请求/秒 | 4591.31 请求/秒 | 2007.70 请求/秒 |

| /user/login(重写) | 126.48 请求/秒 | 128.58 请求/秒 | 117.78 请求/秒 |

该模块在速度上接近纯 Nginx,并优于 Apache 组合。静态内容因 .htaccess 解析而变慢,但通过位置排除进行了优化。

关键要点

  • 该模块完全模拟 mod_rewrite,包括内部重定向和 .htaccess 缓存。
  • 无需模板的 CMS 支持:WordPress、Drupal、Grav 可使用原生 .htaccess。
  • 性能:达到纯 Nginx 的 90–100%,无 Apache 开销。
  • 构建为 RPM/DEB 包,适用于 RHEL/Debian,支持 Docker。
  • 限制:最小化 RewriteMap,简化 RewriteOptions(对 CMS 足够)。

— Editorial Team

Advertisement 728x90

继续阅读