Search code examples
vue.jsnginx

Deploy VUE project on Nginx, static file like css, js can not be found


My OS is window, and deploy VUE project on Nginx server.

  1. Build VUE project cd E:\test\test-project-frontend-demo npm install && npm run build
  2. config nginx:

nginx.conf

worker_processes  1024;

pid                     logs/nginx.pid;

events {
    multi_accept        on;
    worker_connections  65535;
}

http {
    #MIME
    include             mime.types;
    default_type        application/octet-stream;

    #LOGGING
    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          logs/access.log     main;
    error_log           logs/error.log      warn;

    charset             utf-8;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    server_tokens       off;
    log_not_found       off;
    types_hash_max_size 2048;
    client_max_body_size 16M;
    #keepalive_timeout  0;
    keepalive_timeout   65;
    gzip  on;

    #SITES
    include sites-available/project.conf;
}

project.conf

server {
    listen          80;
    listen          443 ssl;

    server_name project.testltd.com;

    # security
    include nginxconfig.io/security.conf;

    # logging
    access_log logs/project.access.log;
    error_log logs/project.error.log warn;

    # site project
    location / {
        alias E:/test/test-project-frontend-demo/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # additional config
    include nginxconfig.io/general.conf;

    # ssl config
    include nginxconfig.io/self-signed.conf;
    include nginxconfig.io/ssl-params.conf;
}

start nginx: nginx.exe -c conf/nginx.conf

enter image description here

index.html can be access , and response is 200, but static file like css and js can not be accessed, Why?


Solution

  • Check if the index.html is using static path like

    <link rel="stylesheet" href="/style.css">
    

    If so, it need to be relative path

    <link rel="stylesheet" href="./style.css">
    

    It can be set in your build tool config file.

    For example, with Vite, in vite.config.js, set "base" option to empty string or "./".