Nginx 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。
安装nginx:
sudo apt-get install nginx
启动nginx(一般都是自动启动的):
格式:nginx安装目录地址 -c nginx配置文件地址
如: /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx启动后,可以通过以下命令进行控制:
nginx -s signal
signal可以是:
- stop — fast shutdown
- quit — graceful shutdown
- reload — reloading the configuration file
- reopen — reopening the log files
其中,quit会等到工作进程服务完现有的请求后才执行:
$ nginx -s quit
查看配置文件:
$ cat /etc/nginx/nginx.conf
nginx.conf 可能在其他路径下,如/usr/local/nginx/conf 或 /usr/local/etc/nginx.
#nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
application/xml application/xml+rss text/javascript;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
从nginx.conf可以看出配置文件的结构:events、http在main环境中,server在http中,location在server中。其中,http中,有两个include:
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
指向/etc/nginx/conf.d/和/etc/nginx/sites-enabled/下的配置文件,其中/etc/nginx/sites-enabled/下的default链接指向/etc/nginx/sites-available/default。
$ cd /etc/nginx/sites-enabled/
$ ls -l
输出:
lrwxrwxrwx 1 root root 34 Sep 12 13:42 default -> /etc/nginx/sites-available/default
例如要配置一个代理服务器,可以直接在/etc/nginx/sites-available/default写进一个server。
首先,先备份default文件:
$ cd /etc/nginx/sites-available/
$ sudo cp default default-backup
在default文件中写入server:
server {
location / {
proxy_pass http://localhost:8080/;
}
location ~ \.(gif|jpg|png)$ {
root /data/images;
}
}
这个server会过滤的请求,所有以 .gif, .jpg, .png 结尾的请求,例如http://localhost/example.png,nginx将会把文件/data/images/example.png响应,如果没有这个文件则返回404error;其他的请求则全部转向代理服务器http://localhost:8080/。
修改完配置,重载一下:
$ nginx -s reload