最近為了練手Vue框架,寫了一個博客項目,昨天剛剛把個人博客部署上線,因為前后端分離,所以使用Ajax來請求后端api接口獲取數據,部署的過程中碰到了一個坑。我只有一個域名,所以想讓一級域名originalix.com
來訪問博客,而使用二級域名demo.originalix.com
來訪問后端頁面并且請求api。
怎么做呢,在查閱了資料以后發現,首先應該在域名供應商中添加一條二級域名的記錄,比如我想使用的是demo。
設置好域名后,在本地ping一下看看能不能ping通過 demo.originalix.com
接下來,ssh進服務器,找到你安裝的nginx,啟動并且配置。
- 安裝nginx
sudo apt-get install nginx
- 重啟nginx
sudo service nginx start
- 進入nginx配置文件
sudo vim /etc/nginx/sites-available/default
在配置文件中可以這樣寫
server {
listen 80;
server_name originalix.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:2368;
}
}
server {
listen 80;
server_name demo.originalix.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8000;
}
}
而我具體是因為后端是Laravel
框架的項目,所以我得配置文件是這樣寫的
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/;
index index.html index.htm index.nginx-debian.html;
# server_name 110.223.38.82;
server_name http://originalix.xyz;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
server {
listen 80;
server_name demo.originalix.com;
root /var/www/originalix/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
之后重啟nginx,并且打開瀏覽器,輸入 demo.originalix.com
就ok了
ps:在整個過程中如果遇到什么問題,比如 nginx啟動失敗。可以看一下這里:
//這個命令可以看一下你的nginx配置文件有沒有問題,
//如果有問題它會指出,做相應的修改,直到沒報錯
nginx -t
//查看日志。比如我nginx -t明明沒問題,老是啟動失敗,
//看了日志才知道 Address already in use,端口被占用o(╯□╰)o
cat /var/log/nginx/error.log
還是那句話,失敗了一定要學會看日志!!!看日志!!!看日志!!!
很簡單的事情,我也是摸索了一會兒,崩潰ing。
所以寫個博客記錄下來,希望能幫助到大家。