Nginx 基础知识

161 阅读1分钟

现在前端文件和后端文件都在服务器中了,且后端已经正常运行了,这时候可以通过配置 nginx 使得我们访问 ip 时直接跳转到博客界面

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /home/www/react_pc;
        index        index.html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
          root      /home/www/react_pc;
          index     index.html;
          try_files $uri $uri/ /index.html;
        }

        location /api {
          rewrite  ^/apis/(.*)$ /$1 break;
          proxy_pass http://localhost:8081/api;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

在阿里云上部署nodejs应用

需要通过一种手段来使项目支持公网IP访问,这种手段————就是ngxin反向代理

随便去下载一个ngxin,然后在ngxin/conf文件夹下新建一个node.conf。

upstream nodejs {
    server 127.0.0.1:3000;
    keepalive 64;
}

server {
    listen 80;
    server_name '';#此处为你的公网IP
    location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass      http://nodejs;

    }

}

然后在同级目录下的nginx.conf中include。


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Methods GET,POST,PUT;
    add_header Access-Control-Allow-Headers accept,content-type,x-iamservice-appid,x-iamservice-appkey;
    
    include       mime.types;
    default_type  application/octet-stream;

   

    sendfile        on;
   

    keepalive_timeout  65;
    include node.conf;

}

node项目还是在localhost上运行,mongodb也开启,在使用localhost:3000能访问项目的情况下,双击执行ngxin或者在ngxin目录下打开cmd执行nginx.exe。

然后使用公网IP访问,非常完美。(就是网速有点慢,还偶尔会重定向,可能是ngxin配置有问题);

线上配置

nodejs默认端口是3000,需要配置nginx反向代理到nodejs的3000端口。

server {
    listen       443;
    server_name  www.domain.com;
    ssl on;
    ssl_certificate /usr/share/nginx/conf/1_www.vuenode.com_bundle.crt;
    ssl_certificate_key /usr/share/nginx/conf/2_www.vuenode.com.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection ‘upgrade’;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}