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 正常顯示

如果還有其他疑問可以留言....

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容