Cách cài Linux, nginx, MySQL, PHP (LEMP) và tối ưu trên Ubuntu 12.04

Bài viết này mình xin đá sang mảng VPS một chút để lưu lại các bước đơn giản cài đặt Linux, nginx, MySQL, PHP (LEMP) và tối ưu trên Ubuntu 12.04. Với tutorial này hi vọng các bạn sẽ yên tâm hơn khi mua các gói giảm giá VPS trong đợt Black Friday sắp tới.

Theo mình tìm hiểu thì LEMP Server tối ưu nhất khi chạy với WordPress. Trước đây blog Chia Sẻ Coupon chạy trên VPS của Linode với server LAMP, tuy nhiên từ khi chuyển qua LEMP mình thấy blog chạy nhanh hơn chút và cũng tốn ít tài nguyên hệ thống hơn.

cai dat lemp

Trong bài này mình sẽ hướng dẫn các bạn cài đặt server VPS để chạy 1 site WordPress. Nội dung tham khảo từ tutorial của DigitalOcean và các nguồn khác trên mạng. Mình khuyên các bạn nên sử dụng VPS của DigitalOcean để test, có vấn đề gì thì Rebuild from Ubuntu Image rất nhanh.

Các bước cài đặt LEMP server

Bạn cần chuẩn bị một server Ubuntu mới tinh chưa cài gì cả, ở đây mình dùng Ubuntu 12.04 64 bit

1. Update Apt-Get

sudo apt-get update

2. Cài đặt MySQL

sudo apt-get install mysql-server php5-mysql

Trong quá trình cài đặt bạn sẽ phải cài đặt root mysql password

Sau khi cài đặt MySQL, kích hoạt bằng lệnh:

sudo mysql_install_db

Hoàn tất cài đặt

sudo /usr/bin/mysql_secure_installation

Điền vào root password

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Sau đó là các thao tác như cài đặt lại password, xóa anonymous user… Cái này tùy bạn setup

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y                                            
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

3. Cài đặt nginx

sudo apt-get install nginx

Chạy nginx

sudo service nginx start

Lúc này bạn có thể truy cập thẳng vào IP/domain để xem nginx đã hoạt động hay chưa

4. Cài đặt PHP

sudo apt-get install php5-fpm

5. Tùy chỉnh PHP

Tùy chỉnh lại php.ini

sudo nano /etc/php5/fpm/php.ini

Tìm dòng cgi.fix_pathinfo=1 (nhấn Ctrl+W trong nano), bỏ dấu ; ở đầu và thay 1 = 0

cgi.fix_pathinfo=0

Lưu lại (Ctrl+O, Enter) và thoát (Ctrl+X)

Tùy chỉnh php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

Tìm dòng listen = 127.0.0.1:9000 và thay 127.0.0.1:9000 thành /var/run/php5-fpm.sock

listen = /var/run/php5-fpm.sock

Lưu và thoát.

Khởi động lại php-fpm

sudo service php5-fpm restart

6. Tùy chỉnh nginx

Mở file virtual host mặc định

sudo nano /etc/nginx/sites-available/default

Tìm và thay đổi cài đặt như bên dưới. Chú ý các phiên bản Ubuntu mới hơn sử dụng ‘htm’ thay vì ‘www’ nên bạn cần chỉnh lại cài đặt tương ứng.

[...]
server {
        listen   80;

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        server_name example.com;

        location / {
                try_files $uri $uri/ /index.php?$args;
        }

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;

        }

}
[...]

Một số thay đổi:

  • Thêm index.php
  • Thay đổi server_name thành tên miền
  • Chỉnh sửa đường dẫn cho phù hợp với permalink của WP
  • Chỉnh lại nội dung trong phần cài đặt “location ~ \.php$ {“

Lưu và thoát.

7. Tạo php info file

Tạo file php.info

sudo nano /usr/share/nginx/www/info.php

Thêm nội dung

<?php
phpinfo();
?>

Lưu và thoát

Khời động lại nginx

sudo service nginx restart

Đã xong, giờ bạn có thể xem các cài đặt của nginx và php-fpm bằng cách truy cập: http://youripaddress/info.php

8. Cài đặt phpMyAdmin

sudo apt-get install phpmyadmin

Khi phpMyAdmin hỏi bạn chọn server (apache or lighttpd) thì chọn cái nào cũng được.

Tạo symbolic link

sudo ln -s /usr/share/phpmyadmin/ /usr/share/nginx/www

Sửa lỗi The mcrypt extension is missing khi chạy phpMyAdmin

Mở file php.ini

sudo nano /etc/php5/fpm/php.ini

Tìm đoạn Dynamic Extensions và thêm dòng sau vào phía cuối

extension=mcrypt.so

Restart php5-fpm

sudo service php5-fpm restart

Khởi động lại nginx

sudo service nginx restart

Giờ bạn đã có thể truy cập vào phpMyAdmin thông qua đường dẫn http://youripaddress/phpmyadmin

9. Tham khảo thêm nếu bạn cần

  • A Basic MySQL Tutorial
  • Install an FTP Server
  • Install and Setup Postfix (mình không cài mail do dùng mail server bên ngoài)

Cài đặt WordPress

Mình sẽ cài đặt WordPress bản mới nhất lấy trên wordpress.org cho đơn giản, còn bạn có thể upload file zip chứa blog và thực hiện tương tự.

1. Tải WordPress

Đến folder www

cd /usr/share/nginx/www

Tải WordPress mới nhất

wget http://wordpress.org/latest.tar.gz

Giải nén

tar -xzvf latest.tar.gz

Nếu bạn tự up file zip lên thì dùng lệnh sau

unzip -q website.zip

2. Tạo WordPress Database and User

Vào MySQL shell, đăng nhập bằng MySQL root password

mysql -u root -p

Tạo database

CREATE DATABASE wordpress;
Query OK, 1 row affected (0.00 sec)

Tạo user

CREATE USER wordpressuser@localhost;
Query OK, 0 rows affected (0.00 sec)

Đặt pass

SET PASSWORD FOR wordpressuser@localhost= PASSWORD("password");
Query OK, 0 rows affected (0.00 sec)

Cấp quyền

GRANT ALL PRIVILEGES ON wordpress.* TO wordpressuser@localhost IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)

Refresh MySQL

FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

Thoát MySQL shell

exit

3. Cài đặt WordPress

Tạo file wp-config.php

cp wordpress/wp-config-sample.php wordpress/wp-config.php

Chỉnh thông số

sudo nano wordpress/wp-config.php

Chú ý thông tin để kết nối database

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'wordpressuser');

/** MySQL database password */
define('DB_PASSWORD', 'password');

Lưu và thoát

4. Copy files

sudo cp -r wordpress/* /usr/share/nginx/www

Set ownership của www để không bị lỗi yêu cầu connection information khi cài plugin hoặc update WordPress. Lưu ý thay đổi “username”

sudo chown www-data:www-data * -R 
sudo usermod -a -G www-data username

Giờ thì bạn có thể truy cập vào IP VPS hoặc domain để tiến hành cài đặt WordPress.

Tối ưu LEMP

1. Tự khơi động lại server khi hết bộ nhớ

sudo nano /etc/sysctl.conf

Thêm vào dưới cùng 2 dòng sau

vm.panic_on_oom=1
kernel.panic=10

The vm.panic_on_oom=1 line enables panic on OOM; the kernel.panic=10 line tells the kernel to reboot ten seconds after panicking.

2. Tự động optimize MySQL table hàng tuần

Mở file crontab

crontab -e

Thêm dòng sau vào dưới cùng

@weekly mysqlcheck -o --user=root --password=<your password here> -A

Bạn có thể tự chạy mysqlcheck trước để xem câu lệnh đúng chưa

3. Kích hoạt Gzip Compression

Mở file cài đặt nginx

sudo nano /etc/nginx/nginx.conf

Chỉnh phần cài đặt gzip

gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

4. Make Browsers Cache Static Files On nginx

Thủ thuật này bắt trình duyệt sẽ phải lưu cache các file tĩnh (images, CSS và Javascript) và load lại chúng thay vì gửi yêu cầu tới server tải lại.

Mở file virtual host mặc định

sudo nano /etc/nginx/sites-available/default

Thay đổi cài đặt như bên dưới.

[...]
server {
        [...]
        location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$  {
              expires 365d;
        }
        [...]
}
[...]

Giờ thì bạn đã có một server LEMP chạy mượt mà như của Chia Sẻ Coupon rồi đó. Nếu bạn gặp vấn đề gì trong quá trình cài đặt có thể comment bên dưới, nếu biết mình sẽ trả lời ngay.

Ngoài ra, server này mình cài rất đơn giản để đảm bảo performance, nếu bạn thấy trong quá trình chạy WordPress mà thiếu package nào thì comment lại để mình bổ sung cho bài viết hoàn chỉnh hơn nhé.

Leave a reply:

Your email address will not be published.

Site Footer