Nginx入门

689 查看

1.安装

brew install nginx

Mac配置目录:

/usr/local/etc/nginx/nginx.conf

2.常用命令

nginx -s stop 

nginx -s quit  // 安全的停止服务(比如等到当前正在的请求完成后才结束进程)

nginx -s reload  // 重新加载配置文件

nginx -s reopen  // 重新打开日志文件

注:

nginx -s quit

This command should be executed under the same user that started nginx.

3.完整配置样本

user www;

worker_processes 12;

error_log /var/log/nginx/error.log;

pid /var/run/nginx.pid;

events {
    use /dev/poll;
    worder_connections 2048;
}

http {
    include /opt/local/etc/nginx/mime.types;
    default_type application/octet-stream;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    server_names_hash_max_size 1024;
}

server {
    listen 80;
    return 444;
}

server {
    listen 80;
    server_name www.example.com;
    location / {
        try_files $uri $uri/ @mongrel;
    }
    location @mongrel {
        proxy_pass http://127.0.0.1:8080;
    }
}

Nginx是由指令控制的模块组成的,指令分简单指令和块指令。简单指令由name,parameters(通过空格分开)和分号组成。块指令拥有相同的结构,只不过是以{ }结尾。若块指令还包含其他指令,则称为context(例如:events http,server,location)。

4.http模块

Serving Static Content

web服务器最重要的一项功能就是为静态提供服务。接下来就是做两个实例,实现访问静态html和图片。

在本地新建两个目录:

/data/www

/data/image

分别添加一个index.html和一个test.jpg图片到里面。

打开nginx.conf在http块指令下添加:

server {
    listen 1234;//不要和配置里面的其他端口重复,默认80
    
    location / {
        root /data/www;
    }
    
    location /image/ {
        root /data/image;
    }
}

重新加载配置:

nginx -s reload

打开浏览器分别访问:

http://localhost:1234/index.html

http://localhost:1234/image/t...

就能看到相应的内容。

Setting Up a Simple Proxy Server

Nginx另一个经常用到的功能是代理,通俗点就是中转站。

在配置文件里新增一个server:

server {
    listen 1200;
    location / {
        proxy_pass https://www.baidu.com/;
    }
}

此时访问:http://localhost:1200,就会看到百度首页。

原文:http://www.jianshu.com/p/9c0c...