直接在Nginx中用server_name匹配无www域名并return 301跳转至带www的HTTPS URL;需同时配置80和443端口,避免rewrite、$scheme及DNS解析等问题。

Nginx Hosting
通过服务器本地nginx实例实现零认证静态游戏托管。作为所有浏览器游戏的主要部署方式,无需登录、无需令牌、无需用户操作。
下载
<p>直接在 Nginx 配置中为不带 www 的域名设置 301 重定向,核心是用 <strong>server_name</strong> 匹配无 www 域名,再用 <strong>return 301</strong> 跳转到带 www 的完整 URL。</p>
<H3>基础写法(推荐)</H3>
<p>这是最简洁、高效的方式,适用于主站域名(如 example.com → www.example.com):</p>
<font color="#666">
<pre>
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
</font>
<p>说明:<br>
• <strong>server_name example.com</strong> 精确匹配不带 www 的请求<br>
• <strong>return 301</strong> 是强制跳转,比 rewrite 更快、更语义明确<br>
• <strong>$request_uri</strong> 保留原始路径和查询参数(如 /a/b?x=1 → /a/b?x=1)</p>
<H3>HTTPS 场景下必须同时处理 443 端口</H3>
<p>如果站点启用了 HTTPS,仅配置 80 端口无法覆盖直接访问 https://example.com 的情况。需单独加一个 HTTPS server 块:</p>
<font color="#666">
<pre>
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
return 301 https://www.example.com$request_uri;
}
</font>
<p>注意:<br>
• 必须提供有效的证书,否则该 server 块会因 SSL 加载失败而无效<br>
• 不要省略 ssl 配置,否则 Nginx 启动会报错</p>
<H3>避免常见陷阱</H3>
<ul>
<li><strong>不要混用 rewrite 和 return</strong>:rewrite + permanent 也能实现 301,但 return 更轻量、无正则开销,且不会触发 location 重匹配</li>
<li><strong>不要写成 $scheme://www... 形式</strong>:$scheme 在 HTTP/HTTPS 混合场景下可能出错(比如反向代理后 scheme 不准确),显式写死 https:// 更可靠</li>
<li><strong>确保 www 版本的 server 已正确配置并监听对应端口</strong>:否则跳过去会 502 或连接拒绝</li>
<li><strong>检查 DNS 解析</strong>:example.com 和 www.example.com 都需解析到同一台服务器 IP,否则跳转后无法访问</li>
</ul>
<H3>批量处理多个域名(可选)</H3>
<p>若托管多个站点,可用 map 指令统一管理跳转规则:</p>
<font color="#666">
<pre>
map $host $redirect_to {
example.com www.example.com;
blog.example.com www.blog.example.com;
default "";
}
server {
listen 80;
server_name example.com blog.example.com;
if ($redirect_to) {
return 301 https://$redirect_to$request_uri;
}
}
</pre>
</font>
<p>说明:<br>
• map 提前定义跳转目标,便于维护<br>
• if 块配合使用(注意:if 在 location 外可用,此处安全)<br>
• default "" 可防止未匹配域名意外跳转</p>