1. 安裝nginx
sudo apt-get install nginx
2. 配置網站配置檔
正常來說,nginx的網站配置檔會在「/etc/nginx/sites-available」之下,並建一個Symbolic link至「/etc/nginx/sites-enabled」下。
所以會看到「/etc/nginx/nginx.conf」有一句「 include /etc/nginx/sites-enabled/*;」,因此可以為每個網站建立不同的配置檔。
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
...
include /etc/nginx/sites-enabled/*;
...
}
這時候我們可以在「/etc/nginx/sites-available」建立一個用來放網站配置的配置檔
sudo vim /etc/nginx/sites-available/your-domain.name
然後建立軟連結至「/etc/nginx/sites-enabled」之下
sudo ln -sf /etc/nginx/sites-available/your-domain.name /etc/nginx/sites-enabled/your-domain.name
測試配置是否正常,並重新啟動Nginx伺服器
sudo nginx -t
sudo systemctl restart nginx
2. 常見配置方式
配置HTTP (80 port)
轉發至localhost:3000並啟用index
server {
listen 80;
listen [::]:80;
index index.html;
server_name your-domain.name; # 若沒有domain的話,該行可以拿掉
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
轉發至docker啟用的網站,並設定允許上傳大小及根目錄
server {
root /var/www/html;
listen 80;
listen [::]:80;
server_name your-domain.name;
location / {
proxy_pass http://localhost:5000;
proxy_redirect off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
client_max_body_size 256M;
}
配置HTTPS (SSL 443 port)
設定SSL並轉發80至443
server {
root /var/www/html;
listen [::]:443 ssl ipv6only=on;
listen 443 ssl;
server_name your-domain.name;
ssl_certificate /etc/letsencrypt/live/your-domain.name/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your-domain.name/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
location / {
proxy_pass http://localhost:5000;
proxy_redirect off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
client_max_body_size 256M;
}
server {
if ($host = your-domain.name) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name your-domain.name;
return 404;
}