Cài đặt server Linux cơ bản (Centos 7)
Ở đây ta chỉ tập trung vào LEMP (Linux, Nginx, MySQL, PHP). Về database ta sẽ sử dụng MariaDb thay cho Mysql.
Cài đặt chung
Upgrade latest version:
Cập nhật toàn bộ các package, chạy phiên bản mới nhất của server.
# Run as root account
# Step 1: Check current CentOS version
cat /etc/redhat-release
# Step 2: Check for available updates
yum check-update
# Step 2: Package manager cleanup
yum clean all
# Reboot server
reboot
# Step 4: Update CentOS
yum update
# Step 5: Verify current CentOS version
cat /etc/redhat-release
Các gói cài đặt ban đầu:
# Run as root account
# First installation package required
yum group install "Development Tools"
# Vim: vi editor, Git, wget, yum-utils
yum install vim git wget yum-utils
.....
Set static IP for server
vi /etc/sysconfig/network-scripts/ifcfg-eth0
# -- Thay đổi các giá trị trong file ifcfg-eth0
....
TYPE="Ethernet"
DEVICE="eth0"
BOOTPROTO="none"
ONBOOT="yes"
# Server IP #
IPADDR=[ip_192.168.50.20]
# Subnet #
PREFIX=24
# Set default gateway IP #
GATEWAY=[gateway_192.168.50.1]
# Set dns servers if need #
DNS1=8.8.8.8
DNS2=8.8.4.4
....
# -- Restart network service
systemctl restart network
# Kiểm tra IP
ip a s eth0
# Verify new routing settings
ip r
Quản lý, tạo User cài đặt
# -- See https://wiki.archlinux.org/title/users_and_groups
# -- Các files quản lý user và group
/etc/shadow Secure user account information
/etc/passwd User account information
/etc/gshadow Contains the shadowed information for group accounts
/etc/group Defines the groups to which users belong
# -- To add a new user, use the useradd command:
useradd -m -G [additional_groups] -s [login_shell] [username]
-m/--create-home : the user's home directory is created as /home/username. The directory is populated by the files in the skeleton directory. The created files are owned by the new user.
-G/--groups : a comma separated list of supplementary groups which the user is also a member of. The default is for the user to belong only to the initial group.
-s/--shell : a path to the user's login shell. Ensure the chosen shell is installed if choosing something other than Bash. The default shell for newly created user can be set in /etc/default/useradd.
Ex:
useradd -m ducbui
# -- User no login
useradd -s /usr/bin/nologin website
# -- change password
passwd ducbui
# -- Add group
groupadd [groupname]
# -- Thêm user vào group
usermod -aG [additional_groups] [username]
Mục đích chạy các lệnh bằng user cài đặt thường, khi nào cần quyền root thì sudo lên.
# Toàn bộ câu lệnh chạy bằng acc root, nếu user chạy không phải root thì dùng thêm lệnh sudo trước câu lệnh chạy để xin quyền
# Install sudo package if need:
yum install sudo
# 1.Create a new user
adduser [username]
# 2.Set password
passwd [username]
# --- For CentOS and Fedora
# 3.Opens the sudoers file for editing.
visudo
# 4.Add the following line to the file. Replace username with the name of the user that you created in first step:
[username] ALL=(ALL) ALL
# --- For Debian and Ubuntu
# 3.Add user to the sudo group
usermod -aG sudo [username]
# 4.Verify sudo privileges
sudo -l -U [username]
groups [username]
# 5.Switch to user and test whether sudo works
su [username]
Ex:
sudo useradd ducbui
sudo usermod -aG sudo ducbui
sudo -l -U ducbui
sudo su ducbui
Disable SSH logins for root.
Không cho phép root login, phải dùng user thường rồi sudo.
# 1.Log in to the server as root using SSH.
# 2.Open the /etc/ssh/sshd_config file in your preferred text editor (nano, vi, etc.).
# 3.Locate the following line:
PermitRootLogin yes
# Modify the line as follows:
PermitRootLogin no
# *** This step is crucial. If you do not add the user to the list of allowed SSH users, you will be unable to log in to your server!
# 4.Add the following line. Replace username with the name of the user you created in the previous procedure:
AllowUsers [username]
# 5.Save the changes to the /etc/ssh/sshd_config file, and then exit the text editor.
# 6.Restart the SSH service
# For CentOS and Fedora
service sshd restart
# For Debian and Ubuntu
service ssh restart
Mở port truy cập cho các dịch vụ
# -- mysql
sudo firewall-cmd --permanent --add-port=3306/tcp
# -- http
sudo firewall-cmd --permanent --add-port=80/tcp
# -- https
sudo firewall-cmd --permanent --add-port=443/tcp
# -- reload firewall
firewall-cmd --reload
# -- list port
firewall-cmd --list-ports
firewall-cmd --zone=public --list-ports
Sử dụng ps -aux và Netstat kiểm tra các process đang chạy và Port đang sử dụng
# -- Dùng ps để kiểm tra các tiến trình đang chạy
ps -aux -P | grep '[noi dung]'
# Ex: ps -aux -P | grep 'nginx'
Sử dụng netstat để kiểm tra các cổng đang mở, nó là 1 phần của gói công cụ mạng net-tools
sudo yum install net-tools
netstat -tulpn
# Ex: netstat -tulpn | grep 80
Lets discuss the flags used with the netstat command below. -t : Show only TCP sockets on Linux -u : Display only UDP sockets on Linux -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server. -p : List process name that opened sockets -n : Don’t resolve service names i.e. don’t use DNS
Tham khảo
Giới thiệu về Linux và các Distro Linux
Cài đặt database
Cài đặt MYSQL
Để cài đặt MySQL, bạn cần truy cập repository Yum của MySQL, nơi cung cấp các package cho MySQL. Tìm phiên bản cần cài đặt. Download về server
wget http://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm
Prepare repository rồi cài đặt MySQL packages từ nó.
sudo rpm -ivh mysql57-community-release-el7-9.noarch.rpm
Cài đặt MySQL ngay bằng dòng lệnh yum install.
sudo yum install mysql-server
Khởi động Mysql
# -- Start
sudo systemctl start mysqld
# -- Status
sudo systemctl status mysqld
Lưu ý: MySQL được tự động kích hoạt khi khởi động máy vì đây là thiết lập mặc định. Bạn có thể thay đổi bằng lệnh
sudo systemctl disable mysqld.
Trong quá trình cài đặt, một mật khẩu tạm thời được tạo cho người dùng root MySQL. Xác định vị trí file mysqld.log bằng lệnh này:
sudo grep 'temporary password' /var/log/mysqld.log
Output
2022-01-24T19:54:46.313728Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: mqRfBU_3Xk>r
Ghi lại mật khẩu vì bạn phải thay đổi mật khẩu trong bước tiếp theo để bảo mật quá trình cài đặt. Policy mật khẩu yêu cầu 12 ký tự, có ít nhất một chữ hoa, một chữ thường, một con số và một ký tự đặc biệt.
Lưu ý: Các cấu hình trong Mysql có thể xem thêm trong phần Mariadb
Cài đặt MARIADB
Cài đặt
Bởi vì MariaDB được các lập trình viên của MySQL thiết kế và quản lý để thay thế cho MySQL. Nên chúng ta có thể dễ dàng cài đặt bằng lệnh sudo yum install mysql
# -- Cài đặt mariadb-server
sudo yum install mariadb-server
Khởi động mariadb
sudo systemctl start mariadb
sudo systemctl status mariadb
Cài đặt MariaDB starts/stop at boot:
sudo systemctl enable/disable mariadb
Securing the MariaDB Server
sudo mysql_secure_installation
# -- Nếu không chạy được thì vào thư mục
cd /usr/bin/
sudo mysql_secure_installation
Thực hiện trả lời 1 số câu hỏi để bảo mật hệ thống database
Enter current password for root (enter for none): Nhấn phím Enter
Switch to unix_socket authentication [Y/n]: n
Change the root password? [Y/n]: Y
New password: Nhập password root các bạn muốn tạo
Re-enter new password: Nhập lại password root
Remove anonymous users? [Y/n] : Y
Disallow root login remotely? [Y/n]: Y
Remove test database and access to it? [Y/n] : Y
Reload privilege tables now? [Y/n]: Y
Testing the Installation
mysqladmin -u root -p version
```Output bash mysqladmin Ver 9.0 Distrib 5.5.50-MariaDB, for Linux on x86_64 Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Server version 5.5.50-MariaDB Protocol version 10 Connection Localhost via UNIX socket UNIX socket /var/lib/mysql/mysql.sock Uptime: 4 min 4 sec
Threads: 1 Questions: 42 Slow queries: 0 Opens: 1 Flush tables: 2 Open tables: 27 Queries per second avg: 0.172
```bash
mysql -u root -p
# MaraiDB [(none)]>
Truy cập từ xa
Cho phép các hệ thống khác trong mạng truy cập máy chủ cơ sở dữ liệu, hãy cho phép cổng 3306:
sudo firewall-cmd --add-service=mysql --permanent
# -- OR
# sudo firewall-cmd ––permanent ––add-port=3306/tcp
sudo firewall-cmd --reload
Để kết nối từ xa hoạt động, dịch vụ phải lắng nghe trên một địa chỉ IP chứ không phải giao diện loopback localhost. File /etc/mysql/my.cnf or /etc/mysql/mariadb.conf.d/50-server.cnf
```/etc/mysql/mariadb.conf.d
Listen on specific IP address in the server
bind-address=172.21.200.12
Listen on all available interfaces
bind-address=0.0.0.0
```bash
# Restart mysql when change config
sudo systemctl start mariadb
# Kiểm tra
netstat -ant | grep 3306
Grant Access to a User from a Remote System
Trong trường hợp này chúng ta tạo 1 database, 1 user và cấp quyền truy cập từ xa cho user đó bằng mysql command line
# -- Login with root
mysql -u root -p
# -- Tạo db tên wpdb
MariaDB [(none)]> CREATE DATABASE wpdb;
# -- Tạo user 'wpuser' với 'password'
MariaDB [(none)]> CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'password';
Chỉ cho phép wpuser truy cập database wpdb từ 1 địa chỉ ip xác định (Ex: 208.117.84.50)
MariaDB [(none)]> GRANT ALL ON wpdb.* to 'wpuser'@'208.117.84.50' IDENTIFIED BY 'password' WITH GRANT OPTION;
# -- Cập nhật sự thay đổi và thoát khỏi Mariadb shell
MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> EXIT;
Cho phép truy cập tất cả database
MariaDB [(none)]> GRANT ALL ON *.* to 'wpuser'@'208.117.84.50' IDENTIFIED BY 'password' WITH GRANT OPTION;
Cho phép truy cập từ lớp mạng
MariaDB [(none)]> GRANT ALL ON *.* to 'wpuser'@'208.117.84.%' IDENTIFIED BY 'password' WITH GRANT OPTION;
Cho phép truy cập tất cả các database từ khắp nơi
MariaDB [(none)]> GRANT ALL ON *.* to 'wpuser'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
Install MariaDB on CentOS 7 in 2024 MariaDB/MySQL database on Ubuntu
MySQL Master-Slave Replication Setup with Docker

Docker MySQL Master-Slave Replication Setup MariaDB MaxScale Load Balancing on Docker: Deployment MySQL master-slave replication - build.sh
Install Web Server
Install APACHE Web server
Cài đặt Apache
# -- Check before
sudo yum update httpd
sudo yum install httpd
Edit config file /etc/httpd/conf/httpd.conf
# -- Change
ServerName localhost.domain
# -- To
ServerName 127.0.0.1
Cấu hình Firewalld (Nếu có)
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
# -- OR
sudo firewall-cmd ––permanent ––add-port=80/tcp
sudo firewall-cmd ––permanent ––add-port=443/tcp
# -- Reload
firewall-cmd --reload
Checking your Web Server
# -- Start apache
sudo systemctl start httpd
# -- View status
sudo systemctl status httpd
# -- Reboot server if need
reboot
Chú ý: Nếu thấy vẫn có lỗi thì reboot server
```Output status Redirecting to /bin/systemctl status httpd.service ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled) Active: active (running) since Wed 2019-02-20 01:29:08 UTC; 5s ago Docs: man:httpd(8) man:apachectl(8) Main PID: 1290 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─1290 /usr/sbin/httpd -DFOREGROUND ├─1291 /usr/sbin/httpd -DFOREGROUND ├─1292 /usr/sbin/httpd -DFOREGROUND ├─1293 /usr/sbin/httpd -DFOREGROUND ├─1294 /usr/sbin/httpd -DFOREGROUND └─1295 /usr/sbin/httpd -DFOREGROUND
#### **Managing the Apache Process**
```bash
# -- Để dừng máy chủ web
sudo systemctl stop httpd
# -- Khởi động máy chủ web khi nó bị dừng
sudo systemctl start httpd
# -- Để dừng và bắt đầu lại dịch vụ
sudo systemctl restart httpd
# -- Nếu chỉ đơn giản là thay đổi cấu hình, Apache thường có thể tải lại mà không mất kết nối. Để làm điều này, hãy dùng lệnh sau:
sudo systemctl reload httpd
# -- Theo mặc định, Apache được cấu hình để tự khởi động khi máy chủ khởi động. Nếu tắt nó thì hãy nhập lệnh sau:
sudo systemctl disable httpd
# -- Để bật lại dịch vụ khởi động khi khởi động máy chạy lệnh. Apache bây giờ sẽ tự khởi động khi server khởi động lại.
sudo systemctl enable httpd
Các file cấu hình
.Tất cả các file cấu hình của Apache đều nằm trong thư mục
/etc/httpd. .File cấu hình chính của Apache là/etc/httpd/conf/httpd.conf. .Tất cả các tệp cấu hình đều phải kết thúc bằng.confvà nằm trong thư mục/etc/httpd/conf.d. .Các tệp cấu hình chịu trách nhiệm tải các modules Apache được đặt trong thư mục/etc/httpd/conf.modules.d. .Để quản lý tốt hơn, nên tạo một tệp cấu hình riêng (vhost) cho mỗi tên miền. .Các tệp vhost Apache phải kết thúc bằng.confvà được lưu trữ trong thư mục/etc/httpd/conf.d. Ví dụ: nếu tên miền của bạn là mydomain.com thì tệp cấu hình sẽ được đặt tên/etc/httpd/conf.d/mydomain.com.conf .Các file log của Apache (access_log và error_log) nằm trong thư mục/var/log/httpd/. Bạn nên có file log riêng cho mỗi vhost.
Setting Up Virtual Hosts
Mặc định cấu hình chạy các file html lưu trong thư mục /var/www/html. Mặc dù điều này tốt cho một trang web nhưng sẽ khó sử dụng nếu bạn host nhiều trang web. Thay vì sửa đổi /var/www/html, bạn sẽ tạo folder bên trong /var/www cho trang web example.com. Giữ nguyên /var/www/html làm folder mặc định được phục vụ nếu request của client không phù hợp với trang nào.
# -- Ex domain cần tạo example.com
# -- Tạo folder html cho example.com như sau, sử dụng flag -p để tạo folder cần thiết
sudo mkdir -p /var/www/example.com/html
# -- Log folder nếu cần
sudo mkdir -p /var/www/example.com/log
# -- chỉ định quyền sở hữu folder html với biến $USER
sudo chown -R $USER:$USER /var/www/example.com/html
# -- OR Sử dung apache user group
sudo chown -R apache:apache /var/www/example.com/html
# -- Quyền mặc định cho web
sudo chmod -R 755 /var/www
Tạo trang index.html
sudo vi /var/www/example.com/html/index.html
<html>
<head>
<title>Welcome to Example.com!</title>
</head>
<body>
<h1>Success! The example.com virtual host is working!</h1>
</body>
</html>
Tạo 2 thư mục sẽ chứa file cấu hình:
/etc/httpd/sites-available chứ file cấu hình server từng domain.
/etc/httpd/sites-enabled chứa symbolic link file cấu hình trong sites-available, thể hiện những site mà ta muốn publish.
sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled
Chỉnh sửa cấu hình file yêu cầu Apache tìm kiếm các virtual server trong directory sites-enabled
sudo vi /etc/httpd/conf/httpd.conf
# -- Add this line to the end of the file
IncludeOptional sites-enabled/*.conf
Tạo file virtual host
sudo vi /etc/httpd/sites-available/example.com.conf
```/etc/httpd/sites-available/example.com.conf
Kích hoạt file cấu hình host cho Apache server
```bash
sudo ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/example.com.conf
# -- Nếu muốn gỡ bỏ file cấu hình nào chỉ cần xóa symbolic link:
rm /etc/httpd/sites-enabled/example.com.conf
Restart server apache
sudo systemctl restart httpd
Cài đặt Web Server trên Centos 7 Install the Apache Web Server on CentOS 7
Install NGINX Web server
Cài đặt Nginx
# -- Thêm kho lưu trữ phần mềm EPEL
sudo yum install epel-release
# -- Cài đặt Nginx
sudo yum install nginx
Khởi động và kiểm tra Nginx server
# -- Cho phép cổng dịch vụ http, https
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
# -- Khởi động Nginx
sudo systemctl start nginx
# -- Kiểm tra trạng thái dịch vụ
sudo systemctl status nginx
Chú y: Managing the Nginx Process cũng giống như Apache: start, stop, reload, enable, disable
Truy cập http://server_domain_name_or_IP/ để thấy kết quả.
If you receive a ‘test failed’ error message for the nginx.conf file, you might be facing an IP address issue. Open the main configuration file, /etc/nginx/nginx.conf.
# Find and comment out the following line:
listen [::]:80 default_server;
# -- Change to
# listen [::]:80 default_server;
# -- Save the changes you have made and reload the Nginx service.
sudo systemctl reload nginx
Exploring and Configuring Nginx. Các thư mục quan trọng trong Nginx
/usr/share/nginx/html - Đây là thư mục chứa nội dung mã nguồn website. Chúng ta không dùng thư mục này cho virtual host mà dùng nó như một default host cho Nginx server.
/etc/nginx/ - Thư mục chứa các file cấu hình của Nginx.
/etc/nginx/nginx.conf - File config chính Nginx.
/etc/nginx/conf.d - Configuration files folder. Files that end with .conf in that directory will be loaded when Nginx is started.
/etc/nginx/conf.d/default.conf - The default server block configuration file that ships with Nginx.
/etc/nginx/sites-available/ - Thư mục chứa các file cấu hình server block.
/etc/nginx/sites-enabled/ - Thư mục chứa Danh sách các server blocks được kích hoạt.
/var/log/nginx/access.log - Chứa các lịch sử request tới Web server của bạn (Bạn có thể thay đổi việc lưu log lại hay không).
/var/log/ngins/error.log - Chứa các lỗi từ Nginx.
Cấu hình server block (virtual host)
Ta cũng thực hiện như server Apache. Tạo các file cấu hình rồi tạo symbolic link file vào thư mục /etc/nginx/sites-enabled/ để kích hoạt lên
# -- Kiểm tra và tạo thư mục nếu chưa tồn tại
sudo mkdir /etc/nginx/sites-available /etc/nginx/sites-enabled
# -- Chú ý change owner nếu cần thiết
# sudo chown -R $USER:$USER /etc/nginx/sites-available /etc/nginx/sites-enabled
# -- Ex domain cần tạo example.com
# -- Tạo folder html cho example.com như sau, sử dụng flag -p để tạo folder cần thiết
sudo mkdir -p /var/www/example.com/html
# -- Log folder nếu cần
sudo mkdir -p /var/www/example.com/log
# -- chỉ định quyền sở hữu folder html với biến $USER
sudo chown -R $USER:$USER /var/www/example.com/html
# -- Quyền mặc định cho web
sudo chmod -R 755 /var/www
Tao trang index.html
sudo vi /var/www/example.com/html/index.html
<html>
<head>
<title>Server cua toi</title>
</head>
<body>
<h1>Xin chao the gioi</h1>
</body>
</html>
Chỉnh sửa cấu hình file Nginx, yêu cầu load file virtual server *.conf trong directory /etc/nginx/sites-enabled
sudo vi /etc/nginx/nginx.conf
# -- Tìm dòng .. trong group 'http { ... }'
include /etc/nginx/conf.d/*.conf;
# Thêm vào bên dưới
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*.conf;
Tạo file domain config
sudo vi /etc/nginx/sites-available/example.com.conf
server {
listen 80;
listen [::]:80;
# Thu muc web
root /var/www/example.com/html;
index index.html;
# Cac domain
server_name example.com www.example.com;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ =404;
}
}
Kích hoạt file cấu hình virtual host
sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf
# -- Nếu muốn gỡ bỏ file cấu hình nào chỉ cần xóa symbolic link:
rm /etc/nginx/conf.d/example.com.conf
Sau khi lưu lại file, bạn sẽ kiểm tra config có đúng syntax không:
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Khởi động lại server. Truy cập domain http://example.com
sudo systemctl restart nginx
Install Nginx on Centos 7 Install Virtual host on Nginx
Install HTTPS NGINX Web Server
Tạo SSL certificate cho web server
Chúng ta có thể đăng ký SSL cert để kiểm thử trên local bằng openssl. Sử dụng domain example.com. Certificate Signing Request (CSR). Khi dùng cách này tạo Certificate Authority thì biểu tượng SSL trên browse truy cập sẽ báo lỗi do chứng chỉ của chúng ta không phải do một tổ chức chính thống cấp.
# -- Cài đặt openssl nếu cần
sudo yum install openssl
Tạo SSL certificate
openssl req -new -newkey rsa:2048 -nodes -keyout example.com.key -out example.com.csr
Let’s break down the command to understand.
-openssl req: It denotes a new openssl request.
-new: New request
-newkey rsa:2048: It creates a 2048-bit RSA key
-nodes: It dosen’t encrypt the key which is not recommended. We are showing this just for demo.
-keyout: It takes the private key as an argument and send that key to the CSR file example.com.csr
-out: This writes the CSR to a file. example.com.csr in our demo.
Input the required details. If you enter '.', the field will be left blank.
Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]:Karnataka Locality Name (eg, city) []:Bengaluru Organization Name (eg, company) [Internet Widgits Pty Ltd]:TheSecMaster Organizational Unit Name (eg, section) []:IT Security Common Name (e.g. server FQDN or YOUR name) []:example.com Email Address []:user@example.com Please enter the following ‘extra’ attributesto be sent with your certificate request A challenge password []:12345 An optional company name []:TheSecurityMaster
Sau khi nhập thông tin ta sẽ được 2 file example.com.key , example.com.csr trong thư mục hiện tại. Để xem nội dung file.
cat example.com.csr
File private key quan trọng chúng ta phải giữ cẩn thận. Chúng ta có thể tạo nhiều file .crs từ file .key
# -- Chú ý đúng kiểu mã hóa
openssl req -newkey rsa:2048 -keyout example.com.key -out mycsr.csr
How to Create a Certificate Signing Request on a Linux Server?
Setup SSL NGINX Server
Trong ví dụ này ta sẽ tạo SSL cho domain example.com. Tạo cấu trúc lưu trữ SSL
mkdir -p /etc/nginx/ssl/example.com
Copy 2 file ssl certificate example.com.crt, example.com.key đã được tạo vào thư mục ssl/example.com
Edit file cấu hình domain /etc/nginx/sites-available/example.com.conf
sudo vi /etc/nginx/sites-available/example.com.conf
server {
listen 80; # Cho phep http, có thể bỏ dòng này để ko chấp nhận http
listen 443 ssl http2; # Su dung https
# Thu muc web
root /var/www/example.com/html;
index index.html index.htm;
# Cac domain
server_name example.com www.example.com;
# 2 file này được tạo thông qua bước tạo SSL Certificate
ssl_certificate /etc/nginx/ssl/example.com/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
# Co the su dung PEM file
# ssl_certificate /etc/example.com/fullchain.pem;
# ssl_certificate_key /etc/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; # Các protocal cho phép, bỏ các phiên bản cũ hơn
ssl_prefer_server_ciphers on;
ssl_ciphers TLS-CHACHA20-POLY1305-SHA256:TLS-AES-256-GCM-SHA384:TLS-AES-128-GCM-SHA256:HIGH:!aNULL:!MD5; ssl_session_cache shared:SSL:40m;
ssl_session_timeout 4h;
ssl_session_tickets on;
add_header Strict-Transport-Security "max-age=31536000" always;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ =404;
}
}
# -- Test the Nginx configuration
sudo nginx -t
# -- Restart
sudo systemctl restart nginx
Step-By-Step Procedure To Install SSL/TLS Certificate On Nginx Web Server! How Properly Configure Nginx Server for TLS Configure Multiple Sites with a Single Certificate
Install PHP-FPM with NGINX Web Server
Install PHP-FPM
Phiên bản PHP trên Centos 7 đã bị out update. Nên ta sẽ dùng third-part package repository để cài đặt PHP. Remi là kho lưu trữ phổ biến, cung cấp các bản PHP cập nhật mới nhất cho máy chủ Centos 7
# -- install the Remi repository for CentOS 7
sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
# -- To check which PHP 7+ releases are available in the Remi repository
yum --disablerepo="*" --enablerepo="remi-safe" list php[7-9][0-9].x86_64
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* remi-safe: mirrors.ukfast.co.uk
Available Packages
php70.x86_64 2.0-1.el7.remi remi-safe
php71.x86_64 2.0-1.el7.remi remi-safe
php72.x86_64 2.0-1.el7.remi remi-safe
php73.x86_64 2.0-1.el7.remi remi-safe
php74.x86_64 1.0-3.el7.remi remi-safe
php80.x86_64 1.0-3.el7.remi remi-safe
PHP 7 cho tốc độ thực thi code nhanh hơn và hiện đã được sử dụng rộng rãi. Vì vậy ta sẽ cài đặt và cấu hình Nginx với php-fpm cho PHP 7. Chúng ta sẽ kích hoạt gói Remi cài đặt PHP 7.4
# -- To enable the correct Remi package to get PHP 7.4 installed
sudo yum-config-manager --enable remi-php74
# -- Nếu gặp lỗi
# sudo: yum-config-manager: command not found
# -- Thì cần cài đặt yum-utils trước
# sudo yum install yum-utils
# -- Chúng ta cũng có thể tắt các gói không cần thiết, tránh cài module nhiều phiên bản
# Disable remi-php70
sudo yum-config-manager --disable remi-php70
Cài đặt PHP và các modules cần thiết
# -- Simple
sudo yum install php php-mysqlnd php-fpm
# -- Cài đặt thêm modules
sudo yum install php php-fpm php-mysqlnd php-zip php-devel php-gd php-mcrypt php-mbstring php-curl php-xml php-pear php-bcmath php-json php-pdo php-pecl-apcu php-pecl-apcu-devel
# -- Kiểm tra các phần mở rộng đã có trong PHP bằng lệnh
php -m
# -- Check version
php --version
PHP 7.4.5 (cli) (built: Apr 14 2020 12:54:33) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
Cấu hình PHP-FPM
File cấu hình php-fpm tại /etc/php-fpm.d/www.conf
sudo vi /etc/php-fpm.d/www.conf
Thay đổi user, group sang nginx
…
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache
…
```/etc/php-fpm.d/www.conf … ; RPM: apache user chosen to provide access to the same directories as httpd user = nginx ; RPM: Keep a group allowed to write in log dir. group = nginx …
By default, `php-fpm` will listen on a specific host and port over TCP (Nginx PHP fastcgi_pass 127.0.0.1:9000). We want to change this setting so it listens on a local socket file, since <u>this improves the overall performance of the server</u>. Change the line containing the `listen` directive to the following:
```/etc/php-fpm.d/www.conf
listen = /var/run/php-fpm/php-fpm.sock
Thay đổi các chỉ thị listen.owner, listen.group và listen.mode
# -- Uncomment. Then, change the owner and group to nginx
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
Save change and start service php-fpm
sudo systemctl start php-fpm
# -- Status
sudo systemctl status php-fpm
# -- Enable
sudo systemctl enable php-fpm
Cấu hình Apache sử dụng PHP-FRM
Cấu hình Nginx sử dụng PHP-FPM
Chúng ta sẽ cấu hình với cài đặt mặc định. Nếu sử dụng cho domain thì khai báo sử dụng php-fpm trong từng domain cụ thể.
sudo vi /etc/nginx/conf.d/default.conf
```/etc/nginx/conf.d/default.conf server { listen 80; server_name [server_domain_or_IP];
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
-- Check systaxt
sudo nginx -t
-- Restart Nginx
sudo systemctl restart nginx
### Kiểm tra PHP Processing trên Web Server
Cấu hình kiểm tra với cài đặt mặc định.
sudo vi /usr/share/nginx/html/info.php
```/usr/share/nginx/html/info.php
<?php
phpinfo();
# -- Set user
sudo chown -R nginx:nginx /usr/share/nginx/html/
# -- Kiểm tra Quyền mặc định cho web
sudo chmod -R 755 /usr/share/nginx/html/
# -- Access to test php pages
http://[server_host_or_IP]/info.php
NGINX Tuning For Best Performance
Chủ đề này còn nhiều vấn đề, tham khảo ở đây.
Use nginx as a Reverse-Proxy with letsencrypt (support SSL)
Giải pháp là chúng ta sẽ tạo một Ngixn server đóng vai trò reverse proxy, nó sẽ phân giải các tên miền và chuyển đến các dịch vụ khác xử lý.
Các dịch vụ ở đây có thể là : web server, services, image resource ... được triển khai bằng hệ thống docker hay khác ... Ngoài ra ta cũng có thể dùng hệ thống docker để phát triển giải pháp này với Nginx Proxy Manager.
Requirements
# -- Install nginx
# -- Thêm kho lưu trữ phần mềm EPEL
sudo yum install epel-release
# -- Cài đặt Nginx
sudo yum install nginx
# -- Stop nginx
sudo systemtcl stop nginx
Install letsencrypt certbot
sudo yum install snapd && sudo snap install --classic certbot
Adding a new app (subdomain)
Đây là ví dụ ta sẽ thêm một ứng dụng mới, service chạy local (via docker) với port 127.0.0.1:8080 cho subdomain là app1.example.com
Chúng ta cần chú ý tạo 2 thư mục
/etc/nginx/sites-available,/etc/nginx/sites-enablednếu chưa tồn tại. Và thêm vào file cấu hình/etc/nginx/nginx.conf``` sudo vi /etc/nginx/nginx.conf
-- Tìm dòng .. trong group 'http { ... }'
include /etc/nginx/conf.d/*.conf;
Thêm vào bên dưới
include /etc/nginx/conf.d/.conf; include /etc/nginx/sites-enabled/.conf; ```
Tạo file cấu hình app1.example.com.conf
# -- create a new file app1.example.com.conf. Dùng YOUR_SUBDOMAIN cho dễ copy/paste sau này
sudo touch /etc/nginx/sites-available/YOUR_SUBDOMAIN.conf
# -- Activate this file
sudo ln -s /etc/nginx/sites-available/YOUR_SUBDOMAIN.conf /etc/nginx/sites-enabled/YOUR_SUBDOMAIN.conf
# -- Edit file .conf
sudo vi /etc/nginx/sites-available/YOUR_SUBDOMAIN.conf
```/etc/nginx/sites-available/YOUR_SUBDOMAIN.conf server { server_name app1.example.com;
# HTTP configuration
listen 80;
listen [::]:80;
# HTTP to HTTPS
if ($scheme != "https") {
return 301 https://$host$request_uri;
} # managed by Certbot
# HTTPS configuration
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/app1.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/app1.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
location / {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $http_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-Proto $scheme;
proxy_read_timeout 900;
}
}
> Không cần lo lắng những file chưa tồn tại, nó sẽ được tạo ra tự động khi ta chạy lệnh `certbot`
> Nhớ thay đổi
> `app1.example.com` bởi subdomain đúng
> `proxy_pass` là thông tin cổng dịch vụ
### Generating letsencrypt certificates
-- Run the next command to generate your certificates
sudo certbot --nginx
Sau khi chạy lệnh này, `certbot` sẽ tự động đọc cấu hình file Nginx và giao tiếp với server **Let’s Encrypt** , chứng thực và tạo ra các file SSL Certificate tại `/etc/letsencrypt/live/[YOUR_SUBDOMAIN]`
### **Tạo multiple apps**
Để thêm các services/subdomain. Ta chỉ cần lập lại các bước trong `Adding a new app (subdomain)`.
### **Automatic certificates refreshing**
Do chứng chỉ Let’s Encrypt’s chỉ có hiệu lực trong 90 ngày. Nên khi hết hiệu lực ta phải chạy để làm mới chứng chỉ.
-- Create a new file in /etc/cron.weekly with content
sudo vi /etc/cron.weekly/certbot
```/etc/cron.weekly/certbot
#!/bin/sh
certbot renew
# -- Make it executable
sudo chmod +x /etc/cron.weekly/certbot
Để kiểm tra quá trình gia hạn, bạn có thể chạy lệnh
sudo certbot renew --dry-run
Use nginx as a reverse-proxy with letsencrypt