02. Nginx Basic Usuage
Folder Structure
How to startup
Nginx & Http
Virtual Machine
server_name to match the domain name.server_name
: the domain name of a server
Matching rules: (Please be careful of the order for domain matching)
- Name matching
server_name www.why.com v.why.com;
- Wildcard matching
server_name *.why.com;
server_name www.why.*;
- Regex Matching:
server_name ~^[0-9]+\.why\.com$;
Reverse Proxy
Tunnel Model
LVS(DR) Model
using proxy_pass
to config reverse proxy.proxy_pass http://www.why.com;
Config A group of server
- Using polling
drawbacks: - can not keep session
upstream httpds {
server 192.168.1.101:80;
server 192.168.1.102:80;
}
server {
listen 80;
server_name *.why.com;
location /{
proxy_pass http://httpds;
}
}
- Using weighting
upstream httpds {
server 192.168.1.101:80 weight=8;
server 192.168.1.102:80 weight=1;
}
- Using
down
sleep the machine
upstream httpds {
server 192.168.1.101:80 weight=8 done;
server 192.168.1.102:80 weight=1;
}
- Using
backup
the backup machine can be used when no others are available.
upstream httpds {
server 192.168.1.101:80 weight=8;
server 192.168.1.102:80 weight=1 backup;
}
- Using
ip_hash
: according to the ip of client to redirect requests to the same server - Using
least_conn
: the least connnection with server - Using
fair
: redirect requests based on the response time of back server.- For accessing resource locate on different server.
- Using
url_hash
: According to the url to redirect requests.
Separation of static and dynamic
Only suits for small website
server {
listen 80;
server why.com
location / {
proxy_pass http://127.0.0.1:8080;
}
location ~*/(js|img|css){
root html;
}
}
URLRewrite
server {
listen 80;
server why.com
location / {
rewrite ^(\d+).html$ index.jsp?pageNum=$1 break;
rewrite ^([0-9]+).html$ index.jsp?pageNum=$1 break;
proxy_pass http://127.0.0.1:8080;
}
}
Info
last: when match with the current pattern, will continue to find new location URI
break: when matching with the current pattern, will stop
redirect: # return 302 redirect, the browser will display the redirect URL
permanent: # return 301 permanent redirect, the browser will display the redirect URL
Difference between redirect
and permanent
: It's the same for users, but different for web crawler.
How to make a high availability
Using [keepalived](https://www.keepalived.org/download.html)
to drift the virtual IP address.
!Configuration File for keepalived
global_defs {
router_id lb111
}
vrrp_instance why{
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200
}
}
!Configuration File for keepalived
global_defs {
router_id lb110
}
vrrp_instance why{
state BACKUP
interface eth0
virtual_router_id 51
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200
}
}
The keepalived
detect whether the instace is alived to work.