谷粒商城nginx
时间: 2025-04-23 20:16:29 浏览: 16
### 谷粒商城 Nginx 配置 示例 教程
#### 修改本地 HOST 文件实现内网穿透
为了使开发环境中的服务能够通过自定义域名访问,需要编辑主机文件 `/etc/hosts` 或 `C:\Windows\System32\drivers\etc\hosts` 添加如下条目[^1]:
```
127.0.0.1 gulimall.com
```
这使得在浏览器输入 `gulimall.com` 时会解析到本机 IP 地址。
#### 设置 HTTPS 和负载均衡
对于生产环境中更安全可靠的连接方式,可以参考官方提供的关于如何配置 NGINX 实现 HTTP 到 HTTPS 的重定向以及设置上游服务器池来分发流量的方法[^2]:
```nginx
server {
listen 80;
server_name gulimall.com;
location / {
rewrite ^ https://$host$request_uri? permanent;
}
}
upstream backend_servers {
least_conn;
server localhost:88 weight=5 max_fails=2 fail_timeout=30s;
}
```
上述代码片段展示了将所有来自第80端口(HTTP)的请求永久性地转向至相同 URL 下的安全版本 (HTTPS),并指定了一个名为 `backend_servers` 的后端集群用于处理实际业务逻辑。
#### 构建反向代理支持跨域资源共享(CORS)
当客户端发起 AJAX 请求给位于不同源的服务端 API 接口时会发生同源策略限制错误。解决办法之一是在 Nginx 中添加 CORS 响应头以便允许特定来源发出预检 OPTIONS 请求和其他类型的跨站点调用[^4]:
```nginx
location /api/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://localhost:88/;
}
```
此段落描述了一个典型的反向代理模式下启用 CORS 支持的方式,在这里任何匹配路径前缀 "/api/" 的请求都会被转发给运行于同一台机器上的 Spring Boot 应用程序实例监听的88号端口上;同时针对 OPTION 方法返回状态码204表示成功响应而无需实体主体内容。
#### 完整案例演示
最后给出一个完整的例子说明怎样利用 Nginx 来构建谷粒商城项目的 Web 服务平台架构[^3]:
```nginx
events { worker_connections 1024; }
http {
upstream api_gateway {
ip_hash;
server 127.0.0.1:88;
}
server {
listen 80 default_server;
root html;
index index.html index.htm;
# Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name gulimall.com www.gulimall.com;
ssl_certificate cert.pem;
ssl_certificate_key privkey.pem;
location / {
try_files $uri $uri/ @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_pass http://api_gateway;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
include snippets/fastcgi-php.conf;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
}
```
这段配置实现了从 HTTP 至 HTTPS 的自动跳转、SSL/TLS 加密通信保障、基于 URI 参数选择静态资源还是动态接口路由决策等功能特性,并且还包含了 PHP-FPM 对 FastCGI 协议的支持部分以供进一步扩展使用场景的可能性。
阅读全文
相关推荐


















