一、Nginx簡介
Nginx是一款輕量級的Web服務器/反向代理服務器,可以作為負載均衡器、HTTP緩存和安全方面的支持。與Apache不同,Nginx的設計原則是預測性地處理IO操作,減少服務器資源的消耗。
這篇指南將介紹如何在Ubuntu 18.04上安裝和配置Nginx,並將其配置為反向代理服務器。
二、安裝Nginx
首先,使用apt-get命令在Ubuntu 18.04上安裝Nginx:
sudo apt-get update sudo apt-get install nginx
安裝完成後,我們可以在瀏覽器中訪問服務器的公共IP地址,確認Nginx是否成功安裝。
三、基本配置
在Nginx的主配置文件中,可以修改默認的Nginx設置。打開配置文件:
sudo nano /etc/nginx/nginx.conf
以下是一些基本的配置調整:
user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
現在重新啟動Nginx服務,以使配置文件生效:
sudo systemctl restart nginx
四、配置反向代理
在Nginx中配置反向代理是一件很容易的事情。可以直接在默認站點的配置文件中,添加反向代理部分。
打開默認站點配置文件:
sudo nano /etc/nginx/sites-available/default
在server段中添加以下配置:
location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
上述配置中,Nginx服務器將會將所有來自於指定端口的請求轉發到本地的3000端口。
完成上述修改後,請驗證配置是否正確:
sudo nginx -t sudo systemctl reload nginx
五、配置SSL證書
如果您沒有購買SSL證書,可以使用Let’s Encrypt提供的免費SSL證書。安裝Certbot:
sudo add-apt-repository ppa:certbot/certbot sudo apt-get update sudo apt-get install python-certbot-nginx
運行Certbot:
sudo certbot --nginx -d example.com -d www.example.com
更新Nginx的SSL配置文件,啟用SSL:
sudo nano /etc/nginx/sites-available/default
修改成以下內容:
server { listen 80; listen [::]:80; root /var/www/example.com; index index.html; server_name example.com www.example.com; location / { try_files $uri $uri/ =404; } location /api/ { proxy_pass http://localhost:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }
這裡將80端口重定向到443端口上,並且啟用SSL安全連接。
重新驗證Nginx配置是否正確,再重啟Nginx服務:
sudo nginx -t sudo systemctl reload nginx
六、總結
Nginx提供了極佳的性能和速度,也是實現反向代理的好工具。在本篇文章中,我們介紹了如何在Ubuntu 18.04上安裝和配置Nginx,並將其配置為反向代理服務器。同時,還演示了如何添加SSL證書,保障你網站的安全性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/302021.html