iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 8
2
Software Development

網頁後端的30件小事系列 第 8

Nginx設置手把手(macOS)

前言

開始前務必先理解server和web server是什麼~

伺服器是什麼?有哪些種類? - StockFeel 股感

網頁伺服器(Web Server)是什麼?-新視野網頁設計

開關Nginx

在終端機輸入nginx開啟Nginx,關閉輸入niginx -s stop
如果遇到權限問題導致開不了,可以去修改檔案權限。

ex: 修改 access.log 和 error.log權限,讓當前使用者可寫入(write)

修改後應該可正常開($ nginx)/關($ nginx -s stop)nginx

config設定檔在哪

不同作業系統和用不同方式安裝Nginx,config檔可能會在不同位置。
那要怎麼知道我的是在哪呢?

可透過試跑config指令$ nginx -t得到路徑,順便檢查config是否有誤。

最簡單的靜態網站設置

編輯nginx.conf,讓設置如下。

然後在/var/tmp/www//var/tmp/images/下分別放入index.html和圖片。

events {}
http {
  server {
    listen 80;
    location / {
      root /var/tmp/www;
    }

    location /images/ {
      root /var/tmp/images;
    }
  }
}

完成上面設置後,當你連到本機的port:80(localhost:80)時,Nginx會回傳根目錄下的index.html。
root /var/tmp/www就是設定根目錄是哪個資料夾,可以自己設定不同位置試試看。

第二段同理,是定義連線到localhost:80/images/時是對應到哪個資料夾。
event{}一定要加,不然會跑錯。

  • 網址輸入127.0.0.1localhost應該會得到index.html的結果。
  • 網址輸入127.0.0.1/images/<圖片名>localhost/images/<圖片名>應該會看到圖片。

反向代理伺服器設置

/var/tmp/up1下放入另一個index.html,內容要跟上一個不同,方便區別。

events {}
http {
  server {
    listen 80;
    location / {
      proxy_pass http://localhost:8080;
    }

    location ~ \.(gif|jpg|png)$ {
        root /var/tmp/images;
    }
  }

  server {
    listen 8080;
    root /var/tmp/up1;

    location / {
    }
  }
}

同時讓nginx跑兩個私服器,一個本體、一個代理。
新開一個server{},路徑下放index.html
proxy_pass把原本進入localhost:80/的請求導到proxy server(localhost:8080)

  • 網址輸入127.0.0.1localhost應該會得到第二個私服器路徑下index的結果。

讓Nginx可以讀php檔

預設的Nginx只能跑html,所以如果你的index是php檔,必須做以下設置。
邏輯大概是讓nginx讀到php檔時,把檔案都給php底下一個叫php-fpm的模組顯示,所以電腦上也必須安裝php。

conf設置如下:

events {}
http {
  server {
    listen 80;
    root /var/tmp/www; #set up root directory
    index index.php; #set up what file to be the index file

    location ~ \.php$ {
        root           /var/tmp/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        include        fastcgi_params;
    }
  }
}

Any files end with .php will be passed to port 127.0.0.1:9000, which is the default port of fpm.

上面設置在做的事,是把所有.php結尾的檔案都丟到127.0.0.1:9000127.0.0.1:9000是php-fpm預設執行的port。


上一篇
路由器 router
下一篇
Apache設置手把手(macOS)
系列文
網頁後端的30件小事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言