1. 程式人生 > >Nginx部署vue專案,Nginx搭建一個靜態資源伺服器

Nginx部署vue專案,Nginx搭建一個靜態資源伺服器

一.Nginx安裝(Centos)

yum install -y nginx

 安裝後啟動nginx

service nginx start

通過ip或者域名訪問以下,看看是不是啟動成功了

二.Nginx部署vue

1.vue專案編譯(推薦vue element-ui框架,方便,開發效率高)

npm run build

2.將編譯好後的dist資料夾上傳到centos伺服器中

3.編輯nginx配置檔案nginx.conf

vi /etc/nginx/nginx.conf

配置檔案內容配置

 server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

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

        location / {
            
        }
        }

include /etc/nginx/default.d/*.conf,我們可以在/etc/nginx/default.d資料夾下配置單個服務。

4.為自己的專案編輯配置檔案(vue專案)

vi  /etc/nginx/default.d/vue.conf

   vue專案配置檔案

server {
        listen       8081;
        server_name  localhost;
        root         /my/app/vue;

        location / {
            try_files $uri $uri/ /index.html;
        }

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

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

5.重啟Nginx或者重新載入。

service nginx restart

service nginx reload

可成功通過8081埠訪問index.html檔案。

三.Nginx同時部署靜態資源服務

    1.編輯靜態資源服務配置檔案

server {
        listen       8002;
        server_name  localhost;
        root         /usr/share/nginx/html;

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

        location / {
        }

         location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$  {
                root /my/images/;
                autoindex on;# 開啟預覽功能
            }

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

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

通過8002埠可以訪問/my/images下的靜態資源。

四.總結

nginx可以同時啟動多個服務,為多個服務提供統一入口。

(經驗積累:nginx啟動或者重啟報錯的時候,要耐心看日誌,不要急躁)