blog-details

Chuẩn bị server

Đã cài đặt sẵn webserver Nginx trên CentOS, có thể tham khảo bài viết cài đặt LEMP trên CentOS

Tạo thư mục chứa website

Ví dụ mình sẽ tạo thư mục ở folder /home/ nhé. Thay example.com bằng domain của bạn.

mkdir -p /home/example.com/public_html

Gán quyền

Đảm bảo cho website hoạt động bình thường

chown -R nginx:nginx /home/example.com/public_html

Cài đặt Virtual Hosts

Thêm file cấu hình .conf cho domain mới

nano /etc/nginx/conf.d/example.com.conf

Sử dụng đoạn code sau:

#
# example.com configuration
#
server {
    listen       80;
    server_name example.com;

    location / {
        root   /home/example.com/public_html;
        index index.php  index.html index.htm;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    error_page  404              /404.html;
    location = /404.html {
        root   /home/example.com/public_html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /home/example.com/public_html;
    }

    # pass the PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        root           /home/example.com/public_html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

Lưu lại và thoát.

Reload Nginx

service nginx reload

Test thử domain

Giờ mình sẽ tạo thử file index.html để test thử domain example.com có hoạt động đúng không nhé.

nano /home/example.com/public_html/index.html

Thêm đoạn code html vào file

<html>
  <head>
    <title>www.example.com</title>
  </head>
  <body>
    <h1>Success: You Have Set Up a Virtual Host</h1>
  </body>
</html>

Lưu và thoát.

Bây giờ bạn hãy test thử với link http://example.com, nếu kết quả hiện ra như bên dưới là thành công.

test thu example.com

Cài đặt thêm Virtual Hosts

Để add thêm nhiều website nữa, bạn có thể lặp đi lặp lại bước trên

Khởi động lại Nginx là tất cả các website sẽ hoạt động.

Đánh giá bài viết