Nginx配置静态资源访问

今天在配置静态资源的时候遇到了很多坑,简单的记录一下以后后人被坑

一.首先,我们默认大家都安装好了nginx并且能够正常访问Welcome to nginx!这个界面了吧
二.然后,我们需要访问静态资源的话,需要在nginx目录下的conf文件中,修改nginx.conf文件

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
         location /images/ {
            root   /home/ftpuser/www/;
            autoindex on;
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #

* 注意:location 这个位置就是我们需要修改的东西,我这个本来是用来上传保存图片的服务器,所以专门建立了一个文件夹来装上传的图片资源

三,主要是要配置这个location

下面进行配置的参数讲解,其实也简单

  • **location /images/ **: 是指你需要访问该localhost下的哪个文件夹,localhost后带的绝对路径,形式:localhost/images/xxxx.jpg
  • root: 是指资源在你的服务器中的绝对路径,这里千万不能出错,要不然会找不到资源返回404错误,我这里是配置了 /home/ftpuser/www/ ,这个路径在访问的时候不会显性展示出来,自己要记得自己存放文件的路径啊
  • **autoindex ** 这里就写on就可以了,自动适配全资源

这些东西都配置完成,重启服务器:

[root@localhost conf]# ../sbin/nginx -s reload
nginx: [error] open() "/var/run/nginx/nginx.pid" failed (2: No such file or directory)

什么! 不让重启,到底是什么文件丢失了啊,我勒个去,真是折腾...
这个时候最直接的办法是先停止或者杀死进程

最快的方法:
root@localhost conf]# ../sbin/nginx
[root@localhost conf]# ../sbin/nginx -s reload

也可以杀死进程:


[root@localhost conf]# ps -aux|grep nginx
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root      9899  0.0  0.1  23864  1432 ?        Ss   00:59   0:00 nginx: master process ../sbin/nginx
root      9902  0.0  0.1  24300  1640 ?        S    00:59   0:00 nginx: worker process
root      9957  0.0  0.0 103276   856 pts/0    S+   01:16   0:00 grep nginx

这个时候我才发现我太天真了,居然两个进程同时启动毫无冲突:

[root@localhost conf]# kill 9 9902
[root@localhost conf]# kill 9 9899

把两个进程都杀死,然后爽歪歪

root@localhost conf]# ../sbin/nginx

其实这里正确的做法是执行./nginx启动nginx,这里可以-c指定加载的nginx配置文件,如下:./nginx -c /usr/local/nginx/conf/nginx.conf

如果不指定-c,nginx在启动时默认加载conf/nginx.conf文件,此文件的地址也可以在编译安装nginx时指定./configure的参数(--conf-path= 指向配置文件(nginx.conf))

好吧,这做个简单的资源访问还要过五关站六将的,有些同学这个时候可能还会遇到403权限的错误
这个时候还是需要在nginx.conf的文件上修改用户的权限配置,打开文件gg一下来到顶部,然后看到

#user nobody

把这个玩意打开,改成root的权限即可

user root

然后测试一下,在/home/ftpuser/www/路径下面放一张图片,1.jpg,然后在用浏览器访问localhost/images/1,jpg 正常显示

如果还有其他疑问可以留言....

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容