Nginx中配置静态资源目录的方式,以Nginx 1.12.0为例:

1、打开配置文件nginx.conf,文件位置为:

/usr/local/nginx/conf/nginx.conf

注意:安装方式不一样,配置文件位置可能不一样。

2、在8008端口上配置静态资源路径ip:8080/static/,在nginx.conf文件中添加如下配置:

    server {
        listen       8008;
        server_name  localhost2;


        location /static {
            root   /home/sam/nginx;
            #expires 30d;
            #access_log off;
            index  index.html index.htm;
        }

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

    }

注意:要保证静态资源目录/home/sam/nginx下有static目录,不然通过ip:8008/static访问不到资源。

或者配置如下:

    server {
        listen       8008;
        server_name  localhost2;


        location / {
            root   /home/sam/nginx/;
            #expires 30d;
            #access_log off;
            index  index.html index.htm;
        }

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

    }

这样通过ip:8008/static就能访问到静态资源目录/home/sam/nginx/static中的资源。

添加后的完整配置内容如下:

user  root;
worker_processes  1;

events {
    worker_connections  1024;
}


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

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /static/ {
            root   /home/sam/nginx;
            #index  index.html index.htm;
        }

        location /oldpage {
            return 301 http://www.baidu.com;
        }

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


    }

    server {
        listen       8008;
        server_name  localhost2;


        location /static {
            root   /home/sam/nginx;
            #expires 30d;
            #access_log off;
            index  index.html index.htm;
        }

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

    }
}

一、配置完成后使用ip:8008/static访问可能会出现403的问题,原因可能如下:

1、由于启动用户和nginx工作用户不一致所致:

1.1 查看nginx的启动用户,发现是nobody,而为是用root启动的:

命令:ps aux | grep "nginx: worker process" | awk'{print $1}'

1.2 将nginx.config的user改为和启动用户一致,

命令:vi conf/nginx.conf

user  root;

2、权限问题,如果nginx没有web目录的操作权限,也会出现403错误。

解决办法:修改web目录的读写权限,或者是把nginx的启动用户改成目录的所属用户,重启Nginx即可解决。

chmod -R 777 /home/sam/

二、配置完成后使用ip:8008/static访问可能会出现404的问题,原因可能如下:

/home/sam/nginx目录下不存在static目录,解决方式:

/home/sam/nginx目录下添加static目录即可。

三、其它问题:

通过查看日志文件:/usr/local/nginx/logs/error.log分析。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐