
本文探讨如何在单一目录下,利用Nginx和PHP同时处理多个域名,并支持静态页面和伪静态页面的访问。
场景描述
假设有两个域名:www.example.com 和 m.example.com,它们都指向同一个目录。我们需要实现:
www.example.com/about.html 直接访问静态页面 about.html。m.example.com/about.html 实际上访问 m.example.com/index.php?page=about,但URL显示为伪静态的 m.example.com/about.html。解决方案
立即学习“PHP免费学习笔记(深入)”;
www.example.com 的静态页面无需特殊配置,只需将 .html 文件放置在服务器目录即可。
对于 m.example.com 的伪静态处理,我们需要在Nginx配置文件中添加规则。
Nginx 配置示例
以下是一个示例Nginx配置文件,实现了上述功能:
server {
listen 80;
server_name www.example.com m.example.com;
root /path/to/your/webroot; # 替换为你的网站根目录
index index.html index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 替换为你的php-fpm socket路径
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* (.*)\.html {
if ($host = m.example.com) {
rewrite ^/(.*)\.html$ /index.php?page=$1 last;
}
}
}配置说明:
server_name: 定义了两个域名。root: 指定网站根目录,请替换为你的实际路径。location ~ \.php$: 配置PHP处理程序,请根据你的PHP-FPM socket路径进行修改。location ~* (.*)\.html: 匹配所有.html结尾的URL。if ($host = m.example.com): 仅当主机名为m.example.com时执行重写规则。rewrite ^/(.*)\.html$ /index.php?page=$1 last;: 将.html URL重写为index.php?page=...,last标志表示重写后不再继续匹配其他location块。通过此配置,www.example.com 将直接提供静态文件,而 m.example.com 将使用伪静态规则,将.html请求转发给PHP处理。 记住替换配置文件中的占位符为你的实际路径和PHP-FPM配置。
以上就是如何在同一个目录下使用Nginx和PHP实现多域名及静态、伪静态页面的共存?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号