Stories

Detail Return Return

Ubuntu 24.04 上部署 nginx + php-fpm - Stories Detail

How to Setup Nginx with PHP-FPM on Ubuntu 24.04

nginx 是一個流行的 web 服務器,以其速度和可靠性而聞名,被許多頂級網站使用。要用 PHP 運行網站,您需要設置 php-fpm,nginx 與 php-fpm 一起處理 PHP 文件並將其顯示給用户,幫助網站更快地加載並處理更多流量。

本教程將幫助您在 ubuntu 24.04 系統上安裝和配置 NGINX 和 PHP-FPM,創建虛擬主機並使用 Let ' s Encrypt SSL 啓用 HTTPS 來保護您的網站。

Step 1: Update Your System

首先,我們需要確保你的系統是最新的。

sudo apt update
sudo apt upgrade -y

Step 2: Install NGINX Server

現在,讓我們安裝 NGINX web 服務器,遵循以下步驟:

(1) 安裝 nginx

sudo apt install nginx

(2) 啓動 nginx 服務

sudo systemctl start nginx

(3) 設置 nginx 開機啓動

sudo systemctl enable nginx

(4) 檢查 nginx 服務狀態

sudo systemctl status nginx

Step 3: Install PHP-FPM

按照以下步驟安裝 PHP-FPM

(1) 安裝 php-fpm

sudo apt install php-fpm

(2) 啓動 php-fpm 服務

sudo systemctl start php-fpm

(3) 設置 php-fpm 開機啓動

sudo systemctl enable php-fpm

(4) 檢查 php-fpm 服務狀態

sudo systemctl status php-fpm

Step 4: Configure NGINX to Use PHP-FPM

讓我們為您的網站創建一個新的主機文件並將其配置為使用 PHP-FPM

(1) 切換到 NGINX sites-available 目錄

cd /etc/nginx/sites-available/

(2) 為網站創建一個新的配置文件,將“example.com”替換為您的實際域名。

sudo nano /etc/nginx/sites-available/example.com

(3) 將以下配置添加到文件中,確保將“example.com”替換為您的實際域名。

server {
  listen 80;
  server_name example.com www.example.com;

  root /var/www/html/example.com;
  index index.php index.html index.htm;

  location / {
    try_files $uri $uri/ =404;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
  }

  location ~ /\.ht {
    deny all;
  }
}

保存並退出配置文件

為您的網站創建文檔根目錄

sudo mkdir -p /var/www/html/example.com

將目錄的所有權分配給當前用户

sudo chown -R $USER:$USER /var/www/html/example.com

設置目錄權限

sudo chmod -R 755 /var/www/html/example.com

創建一個簡單的 PHP 文件來測試您的配置

nano /var/www/html/example.com/index.php

將以下行添加到 index.php 文件中,保存並退出。

<?php phpinfo(); ?>

把網站 example.com 的配置文件軟連接到 sites-enabled 目錄

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

測試 NGINX 配置是否有語法錯誤

sudo nginx -t

如果測試成功,重新加載 NGINX 以應用更改

sudo systemctl reload nginx

打開您的 Web 瀏覽器,然後訪問 http//example.com 您應該可以看到“ PHP Info”頁面,這意味着您的 NGINX 服務器已正確配置為使用 PHP-FPM。

Step 5: Secure Your Website with Let’s Encrypt SSL

要使用 HTTPS 保護您的網站,您可以使用 Let ' s Encrypt SSL,請遵循以下步驟:

(1) 安裝 Certbot

sudo apt install certbot python3-certbot-nginx

(2) 運行 Certbot 獲取並安裝 SSL 證書,按照提示完成安裝。

sudo certbot --nginx

(3) 通過運行演練來驗證 Certbot 自動更新

sudo certbot renew --dry-run

我的開源項目

酷瓜雲課堂-在線教育解決方案

  • course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
  • course-tencent-cloud(酷瓜雲課堂 - github倉庫)
user avatar dhan Avatar u_15745565 Avatar banxiazhimo Avatar mingtiaoiv Avatar winfacter Avatar tencent_blueking Avatar abai_681266b7f0de8 Avatar zailushang_5bdab5b6eaf7d Avatar
Favorites 8 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.