Thứ Sáu, 16 tháng 8, 2013

nginx 3

About Virtual Hosts


Virtual Hosts are used to run more than one website or domain off of a single virtual private server.

Note: according to the nginx website, Virtual Hosts are called Server Blocks on nginx. However, for the sake of easy comparison with Apache, I'll refer to them as virtual hosts throughout this tutorial. 

Intro


Make sure that nginx is installed on your VPS. If it is not, you can quickly install it with 2 steps.
Install the EPEL repository:
 su -c 'rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-7.noarch.rpm'

Install nginx
yum install nginx

Step One— Create a New Directory


The first step in creating a virtual host is to a create a directory where we will keep the new website’s information. 

This location will be your Document Root in the Apache virtual configuration file later on. By adding a -p to the line of code, the command automatically generates all the parents for the new directory.
sudo mkdir -p /var/www/example.com/public_html

You will need to designate an actual DNS approved domain, or an IP address, to test that a virtual host is working. In this tutorial we will use example.com as a placeholder for a correct domain name. 

However, should you want to use an unapproved domain name to test the process you will find information on how to make it work on your local computer in Step Six. 

Step Two—Grant Permissions


We need to grant ownership of the directory to the right user, instead of just keeping it on the root system. You can replace the "www" below with the appropriate username.
sudo chown -R www:www /var/www/example.com/public_html

Additionally, it is important to make sure that everyone is able to read our new files.
sudo chmod 755 /var/www

Now you are all done with permissions.

Step Three— Create the Page


We need to create a new file called index.html within the directory we made earlier.
sudo vi /var/www/example.com/public_html/index.html

We can add some text to the file so we will have something to look at when the the site redirects to the virtual host.
<html>
  <head>
    <title>www.example.com</title>
  </head>
  <body>
    <h1>Success: You Have Set Up a Virtual Host</h1>
  </body>
</html>

Save and Exit

Step Four—Set Up the Virtual Host


The next step is to enter into the nginx configuration file itself.

sudo vi /etc/nginx/conf.d/virtual.conf

The virtual host file is already almost completely set up on your virtual server. To finish up, simply match the following configuration, modifying the server name and file location as needed:
#
# A virtual host using mix of IP-, name-, and port-based configuration
#

server {
    listen       80;
#    listen       *:80;
    server_name  example.com;

    location / {
        root   /var/www/example.com/public_html/;
         index  index.html index.htm;
    }
}

Save and exit.

Step Five—Restart nginx


We’ve made a lot of the changes to the configuration. Restart nginx and make the changes visible.
/etc/init.d/nginx restart

Optional Step Six—Setting Up the Local Hosts


If you have been using an actual domain or IP address to test your virtual servers, you do not need to set up local hosts. However, if you are using a generic domain that you do not own, this will guarantee that, on your computer only, you will be able to customize it. 

For this step, make sure you are on the computer itself, not your VPS. 

To proceed with this step you need to know your computer’s administrative password, otherwise you will be required to use an actual domain name or your IP address to test the virtual hosts.

Assuming that you do have admin access (gained by typing su and entering the correct password) here is how you can set up the local hosts.

On your local computer, type:
nano /etc/hosts

You can add the local hosts' details to this file, as seen in the example below. As long as line with the IP address and server name is there, directing your browser toward, say, example.com will give you all the virtual host details for the corresponding IP address that you designated.
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost

#Virtual Hosts 
12.34.56.789    www.example.com 

However, it may be a good idea to delete these made up addresses out of the local hosts folder when you are done to avoid any future confusion. 

Step Seven—See Your Virtual Host in Action


Once you have finished setting up your virtual host, you can see how it looks online. Point your browser to your domain name or IP address, and you should see that the page displays, "Success—You Have Set Up a Virtual Host"

Adding More Virtual Hosts


To create additional virtual hosts, you can just repeat the process above, being careful to set up a new document root with the appropriate new domain name each time. Then just copy and paste the new Virtual Host information into the nginx Config file, as shown below
#
# A virtual host using mix of IP-, name-, and port-based configuration
#

server {
    listen       80;
#    listen       *:80;
    server_name  example.com;

    location / {
        root   /var/www/example.com/public_html/;
         index  index.html index.htm;
    }
}


server {
    listen       80;
#    listen       *:80;
    server_name  example.org;

    location / {
        root   /var/www/example.org/public_html/;
         index  index.html index.htm;
    }
}

ngnix 2

Mô hình webserver với Nginx + PHP-FPM + MySQL + Memcached đang được nhiều người sử dụng vì mang lại hiệu quả và hiệu suất cao hơn các mô hình khác, trong bài viết này Congnghevps xin giới thiệu đến các bạn cách cài đặt các dịch vụ này trên máy chủ Linux sử dụng hệ điều hành CentOS 6.4.

I. Thêm Repo

Các repo mặt định của CentOS 6.4 có thể thiếu nhiều gói phần mềm do đó nên bổ sung thêm vào trước khi cài đặt, tạo một file congnghevps.repo trong thư mục /etc/yum.repo.d/ với nội dung sau.
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
 
[remi]
name=Les RPM de remi pour Enterprise Linux 6 - $basearch
#baseurl=http://rpms.famillecollet.com/enterprise/6/remi/$basearch/
mirrorlist=http://rpms.famillecollet.com/enterprise/6/remi/mirror
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Sau đó cập nhật repo và update các phần mềm hiện có
II. Cài Đặt Nginx + PHP-FPM + MySQL + Memcached

Sử dụng một lệnh sau để cài đặt tất cả
# yum install nginx php-fpm mysql-server memcached php-cli php-cgi php-mysql php-gd php-memcached php-memcache
Sau đó ấn định các dịch vụ chính tự động start cùng hệ thống
# chkconfig nginx on
# chkconfig mysqld on
# chkconfig memcached on
# chkconfig php-fpm on
Và đừng bao giờ quên đặt passwd của user root trong mysql đầu tiên
# service mysqld start
# mysqladmin -u root -p 'password'
III. Tạo Virtual Hosting Với Nginx

Đây là một file cấu hình virtual hosting trên Nginx, trong file này có những khai báo giúp Nginx có thể nhận ra các file php script và cách xử lý riêng. Các bạn tạo một file trong thư mục /etc/nginx/conf.d với nội dung sau đây nhé :
server {
# Phần đầu tiên khai báo domain và thư mục gốc cho virtual host
        listen          80;
        server_name    [domain của bạn];
        root            [thư mục chứ các file php];
        index          index.html index.php;
        autoindex      on;
 
# Phần hai khai báo cách xử lý các file php script, nếu là file có đuôi .php thì sẽ được chuyển sang địa chỉ 127.0.0.1:9000 để xử lý sau đó lấy lại kết quả và trả về client.
        location ~* \.php$ {
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        }
 
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        access_log off;
        log_not_found off;
        }
 
        location ~ /\. {
        access_log off;
        log_not_found off;
        deny all;
        }
}
IV. Cấu Hình PHP-FPM

File cấu hình PHP-FPM tiêu chuẩn có thể tìm thấy trong mục /etc/php-fpm.d/www.conf, các bạn copy file này ra một file nữa với tên bất kỳ và phần mở rộng là .conf, sau đó thay đổi những nội dung sau đây
; Start a new pool named 'www'.
[tên tùy thích]
listen = [địa chỉ bạn khai báo trong file virtual host ở trên
user = congnghevps # Sử dụng quyền của user này xử lý các file .php
; RPM: Keep a group allowed to write in log dir.
group = congnghevps # Sử dụng quyền của group này xử lý các file .php
Sau đo các bạn restart lại dịch vụ.

Lưu ý với một virtual hosting nên sử dụng một fastcgi_pass khác nhau, có thể thay đổi port, và với mỗi virtual hosting cũng cần một file pool khác nhau, có cùng địa chỉ để chuyển thông tin qua lại.

nginx

Trong bài viết dưới đây, chúng tôi sẽ hướng dẫn các bạn cách cài đặt Nginx - thường gọi là engine x, đây là 1 hệ thống server HTTP mã nguồn mở, hoàn toàn miễn phí, hiệu suất hoạt động cao, độ ổn định cao, tổ hợp chức năng đa dạng, dễ dàng cấu hình, thiết lập và sử dụng ít tài nguyên hệ thống.Cụ thể, chúng ta sẽ cùng nhau tiến hành cài đặt Nginx trên server CentOS 6.0 với PHP5 hỗ trợ qua PHP – FPM và MySQL.
Trong bài thử nghiệm này, chúng ta sẽ dùng hostnameserver1.example.com với địa chỉ IP 192.168.0.100, tùy từng hệ thống khác nhau các bạn hãy thay đổi thông số kỹ thuật sao cho phù hợp. Bên cạnh đó, php-fpm không có sẵn trên repository chính thức của CentOS, nhưng lại có trên Remi RPM với cơ chế phụ thuộc vào EPEL repository, chúng ta có thể kích hoạt cả 2 repository như sau:
rpm --import https://fedoraproject.org/static/0608B895.txt
rpm -ivh http://download.fedora.redhat.com/pub/epel/6/i386/epel-release-6-5.noarch.rpm
rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
yum install yum-priorities
Sau đó, chỉnh sửa /etc/yum.repos.d/epel.repo...
vi /etc/yum.repos.d/epel.repo
Và thêm dòng priority=10 vào phần [epel]:
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
priority=10
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
[…]
Làm tương tự như vậy với phần [remi] trong /etc/yum.repos.d/remi.repo, và thay đổi enabled thành 1:
vi /etc/yum.repos.d/remi.repo
[remi]
name=Les RPM de remi pour Enterprise Linux $releasever - $basearch
#baseurl=http://rpms.famillecollet.com/enterprise/$releasever/remi/$basearch/
mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/remi/mirror
enabled=1
priority=10
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
failovermethod=priority
[remi-test]
name=Les RPM de remi en test pour Enterprise Linux $releasever - $basearch
#baseurl=http://rpms.famillecollet.com/enterprise/$releasever/test/$basearch/
mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/test/mirror
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Cài đặt MySQL 5:

Để tiến hành, chúng ta bắt đầu với câu lệnh:
yum install mysql mysql-server
Sau đó, tạo đường dẫn khởi động dành cho MySQL (và MySQL sẽ tự khởi động mỗi khi hệ thống hoạt động), đồng thời kích hoạt MySQL server:
chkconfig --levels 235 mysqld on
/etc/init.d/mysqld start
Kiểm tra hệ thống mạng đã ở trạng thái kích hoạt hay chưa, sử dụng lệnh:
netstat -tap | grep mysql
Và hệ thống của bạn sẽ hiển thị kết quả tương tự như dưới đây:
[root@server1 ~]# netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2302/mysqld
[root@server1 ~]#
Nếu không, hãy chỉnh sửa file /etc/my.cnf và thêm chú thích tai phần skip-networking:
vi /etc/my.cnf
[...]
#skip-networking
[...]
Sau đó khởi động lại MySQL server:
/etc/init.d/mysqld restart
Chạy lệnh:
mysql_secure_installation
để khởi tạo mật khẩu cho tài khoản root (nếu không thì bất ai cũng có thể truy cập và sử dụng cơ sở dữ liệu MySQL):
[root@server1 ~]# mysql_secure_installation


NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none): <-- nhấn ENTER
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.
Set root password? [Y/n] <-- nhấn ENTER
New password: <-- mật khẩu tài khoản root
Re-enter new password: <-- mật khẩu tài khoản root
Password updated successfully!
Reloading privilege tables..
... Success!

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] <-- nhấn ENTER
... 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] <-- nhấn ENTER
... 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] <-- nhấn ENTER
- 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] <-- nhấn ENTER
... Success!
Cleaning up...

All done! If you've completed all of the above steps, your MySQL
installation should now be secure.
Thanks for using MySQL!

[root@server1 ~]#

Cài đặt Nginx:

Về mặt kỹ thuật, Nginx đã có sẵn dưới dạng gói cài đặt – package dành cho CentOS 6.0 (từ EPEL) có thể được cài đặt như sau:
yum install nginx
Tiếp tục, tạo đường dẫn khởi động cho nginx và kích hoạt dịch vụ đi kèm:
chkconfig --levels 235 nginx on
/etc/init.d/nginx start
Sau đó, gõ địa chỉ IP của web server vào trình duyệt (ví dụ http://192.168.0.100), và chúng ta sẽ nhìn thấy màn hình hiển thị tương tự như dưới đây:

Cài đặt PHP5:

Về mặt bản chất, chúng ta có thể làm cho PHP5 hoạt động trong nginx qua PHP – FPM - FastCGI Process Manager,có thể thay thế chức năng của PHP FastCGI. Chúng ta có thể cài đặt php-fpm cùng với php-cli và một số module PHP5 giống như php-mysql, nếu người dùng muốn sử dụng MySQL từ các đoạn mã PHP như sau:
yum install php-fpm php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mbstring php-mcrypt php-mssql php-shout php-snmp php-soap php-tidy
Sau đó, mở file /etc/php.ini và thiết lập cgi.fix_pathinfo=0:
vi /etc/php.ini
[...]
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting
; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]
Để tham khảo kỹ hơn về lý do tại sao các bạn phải làm như vậy, hãy truy cập vào đây. Bên cạnh đó, để tránh khỏi các lỗi thường gặp như:
[08-Aug-2011 18:07:08] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2
trong /var/log/php-fpm/www-error.log khi chúng ta tiến hành gọi mã PHP trong trình duyệt, các bạn hãy thiết lậpdate.timezone trong file /etc/php.ini như sau:
[...]
[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Europe/Berlin"
[…]
Để tìm đúng thông tin về múi giờ hệ thống đang sử dụng, gõ lệnh:
cat /etc/sysconfig/clock
[root@server1 nginx]# cat /etc/sysconfig/clock
ZONE="Europe/Berlin"
[root@server1 nginx]#
Tiếp theo, tạo đường dẫn khởi động cho php-fpm và kích hoạt dịch vụ này:
chkconfig --levels 235 php-fpm on
/etc/init.d/php-fpm start
PHP-FPM là 1 tiến trình daemon (với đoạn script /etc/init.d/php-fpm) có cơ chế hoạt động cùng với FastCGI server trên cổng 9000.

Thiết lập Nginx:

File thiết lập, cấu hình chính của nginx là /etc/nginx/nginx.conf, chúng ta có thể mở bằng lệnh:
vi /etc/nginx/nginx.conf
Bản chất quá trình thiết lập này tương đối dễ hiểu (các bạn có thể tham khảo thêm tại đây và đây). Trước tiên, chúng ta có thể tăng số lượng các tiến trình xử lý và thiết lập thông số keepalive_timeout về 1 giá trị phù hợp:
[...]
worker_processes 5;
[...]
keepalive_timeout 2;
[...]
Còn các virtual host đã được khởi tạo trong bộ container server {}, việc tiếp theo của chúng ta là chỉnh sửa giá trị mặc định vhost (trong /etc/nginx/nginx.conf) như sau:
[...]
server {
listen 80;
server_name _;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.php index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
[…]
Thông số server_name _; sẽ biến phần này thành vhost mặc định (tuy nhiên, người sử dụng vẫn phải chỉ định rõ ràng giá trị hostname tương ứng, ví dụ như www.example.com). Ở chế độ mặc định, PHP-FPM sẽ luôn lắng nghe các tín hiệu trên cổng 9000, do vậy chúng ta phải thiết lập nginx kết nối tới 127.0.0.1:9000 đi kèm với fastcgi_pass 127.0.0.1:9000. Sau đó, khởi động lai nginx:
/etc/init.d/nginx restart
Tiếp theo, tạo mã PHP sau trong phần /usr/share/nginx/html...
vi /usr/share/nginx/html/info.php
phpinfo();
?>
Việc tiếp theo là gọi file đó ra qua trình duyệt (ví dụ http://192.168.0.100/info.php):
Chúng ta có thể thấy rằng PHP5 đã làm việc, và hoạt động qua FPM/FastCGI, được chỉ ra tại dòng Server API. Nếu kéo chuột xuống phía dưới, chúng ta sẽ thấy tất cả các module đã được kích hoạt sẵn trong PHP5, trong đó có bao gồm cả MySQL:
Mặt khác, PHP – FPM luôn "lắng nghe" các tín hiệu trên cổng 9000 qua địa chỉ 127.0.0.1 ở chế độ mặc định, và chúng ta cũng có thể thiết lập PHP-FPM sử dụng socket Unix để tránh hiện tượng quá tải TCP. Để thực hiện, các bạn hãy mở file cấu hình /etc/php-fpm.d/www.conf...
vi /etc/php-fpm.d/www.conf
và thay đổi dòng listen như dưới đây:
[...]
;listen = 127.0.0.1:9000
listen = /tmp/php5-fpm.sock
[...]
Sau đó, khởi động lại PHP-FPM:
/etc/init.d/php-fpm restart
Tiếp theo, tìm kiếm trong file cấu hình nginx với tất cả các giá trị của vhosts, thay đổi fastcgi_pass 127.0.0.1:9000;thành fastcgi_pass unix:/tmp/php5-fpm.sock;
vi /etc/nginx/nginx.conf
[...]
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass unix:/tmp/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
[...]
Cuối cùng, khởi động lại Nginx:
/etc/init.d/nginx restart
Chúc các bạn thành công!
Một số đường dẫn tham khảo:
Nginx
PHP
MySQL
CentOS