使用NGINX部署Laravel專案詳解
注意:本文系統環境Ubuntu 16.04 LTS
,已安裝php7.2
。我的Laravel
專案檔案位置/var/www/myproject
。
在閱讀文章步驟之前,如果你目前正在執行Apache
的話,請輸入
$ sudo systemctl stop apache2
來停止Apache
的執行。
那麼我們開始,首先我們先安裝
NGINX
:
$ sudo apt-get update
$ sudo apt-get install nginx
完成之後,我們配置一下防火牆:
$ sudo ufw app list
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
可以看到,有三個應用可以選擇,我們這裡使用Nginx Full
(當然,如果不使用SSL
你也完全可以選擇HTTP
):
$ ufw allow "Nginx Full"
由於Nginx
不能原生處理PHP
,我們需要安裝php-fpm
。我安裝的php
版本為7.2
,所以我這裡選擇安裝php7.2-fpm
:
$ sudo apt-get install php7.2-fpm
請根據你伺服器php
的版本號來選擇相應fpm
。安裝完成後,我們需要對php
進行一個安全配置:
$ sudo vim /etc/php/7.2 /fpm/php.ini
找到
# cgi.fix_pathinfo=1
將#
去掉,並將1
改為0
:
cgi.fix_pathinfo=0
儲存退出。接下來重啟php-fpm
:
$ sudo systemctl restart php7.2-fpm
好了,現在
php
配置完成,nginx
安裝完成,我們需要配置vhost
,即nginx
中的server block
。
這裡有個概念先講解一下,類似Apache
的配置,Nginx
配置中也存在sites-available
這個資料夾,不過與Apache
略有不同的是,Nginx
配置完vhost
後,使用symbolic link
將配置檔案連結至sites-enabled
Apache
中使用a2ensite
命令將我們的站點啟用非常類似。
那麼我們首先開啟Nginx
配置:
$ cd /etc/nginx/sites-available
$ cp default mysite.com
可以看到,我們將sites-available
資料夾下的default
配置檔案拷貝後,生成了我們需要修改的名為mysite.com
的配置檔案。開啟這個檔案:
$ vim mysite.com
可以看到,裡面有一段這樣的配置:
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
我們將除了以上配置的其餘配置全部刪除,然後將以上配置反註釋。接下來,我們需要修改其中的配置。
我在文章頭部已經說過,我的Laravel
專案檔案在/var/www/myproject
中,我們假設我們將要使用mysite.com
這個域名作為我們網站地址。那麼我們將以上配置做出修改如下:
server {
listen 80;
listen [::]:80;
root /var/www/myproject/public;
index index.php;
server_name mysite.com www.mysite.com;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
可以看到,我們在server_name
中加上了mysite.com
及www.mysite.com
這個alias
,所以兩者都可以用來訪問我們的專案。
index
後面我們添加了index.php
,因為我們需要php
來動態載入頁面。
接下來我們看到
location / {
try_files $uri $uri/ /index.php?$query_string;
}
這段location
配置非常重要,注意我們在try_files
的最後,添加了/index.php?$query_string
。這一步非常重要,因為為了使Laravel
正常工作,所有的請求都應該被傳遞給Laravel
本身,即所有的請求都被傳遞給了index.php
,Laravel
的應用主檔案。如果這一步沒有配置,那麼我們只能夠開啟專案主頁,其餘頁面將無法跳轉。
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
這一段中我們設定好php-fpm
的相關配置。然後儲存退出。
接下來我們輸入
$ sudo ln -s /etc/nginx/sites-available/mysite.com /etc/nginx/sites-enabled/
以啟用我們的網站。注意:這裡一定要使用絕對路徑,而不能使用相對路徑(例如../sites-available
),切記。
完成後,我們重啟Nginx
:
$ sudo systemctl restart nginx
好了,這樣一來,mysite.com
就成功地被指向我們的專案地址,並且nginx
可以正常處理請求加載出頁面了。