首页 > 网站 > Nginx > 正文

利用Nginx实现反向代理Node.js的方法详解

2024-08-30 12:24:55
字体:
来源:转载
供稿:网友

前言

公司有项目前端是用node.js进行服务器渲染,然后再返回给浏览器,进而解决单页面的SEO问题。项目部署的时候,使用Nginx反向代理Node.js。具体的步骤如下:

(Nginx、Node.js的安装和基本配置直接跳过)

首先我们要在nginx.cnf文件中的http节点打开下面的配置:

http { log_format main '$remote_addr - $remote_user [$time_local] "$request" '   '$status $body_bytes_sent "$http_referer" '   '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile  on; tcp_nopush  on; tcp_nodelay  on; keepalive_timeout 65; types_hash_max_size 2048; include  /etc/nginx/mime.types; default_type application/octet-stream; # 打开这一行的配置 include /etc/nginx/conf.d/*.conf;}

然后每个域名的配置文件就放到这个目录/etc/nginx/conf.d/下,文件后缀以conf结束。

第一种方式,这种简单:

server { listen 80 ; server_name localhost; root /xxx/xxx/hxxydexx/;  #set $my_server_name $scheme://$server_name;  #if ( $my_server_name != https://$server_name ) { # rewrite ^ https://$server_name$request_uri? permanent; #}  error_log /var/log/nginx/hyde_error.log error; access_log /var/log/nginx/hyde_accss.log main;  location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_http_version 1.1; proxy_set_header Connection "";  # 不需要考虑到负载的,就无需配置upstream节点。 proxy_pass http://127.0.0.1:3000; }  error_page 404 /404.html; location = /xxx/xxx/40x.html { } error_page 500 502 503 504 /50x.html; location = /xxx/xxx/50x.html { }}

2.第二种方式,考虑到负载

upstream node { server 127.0.0.1:3000; }server { listen 80 ; server_name localhost; root /xxx/xxx/hxxydexx/;  #set $my_server_name $scheme://$server_name;  #if ( $my_server_name != https://$server_name ) { # rewrite ^ https://$server_name$request_uri? permanent; #}  error_log /var/log/nginx/hyde_error.log error; access_log /var/log/nginx/hyde_accss.log main;  location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_http_version 1.1; proxy_set_header Connection "";  # 配置upstream节点 proxy_pass http://node; }  error_page 404 /404.html; location = /xxx/xxx/40x.html { } error_page 500 502 503 504 /50x.html; location = /xxx/xxx/50x.html { }}

然后重启或者重新载入nginx的配置文件即可。命令如下:

#检查nginx配置文件中语法是否正确nginx -t#重启nginxservice nginx restart#重载配置文件nginx -s reload             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表