系统环境与依赖:
脚本示范的是CentOS 7.6。Ubuntu 18也是可以的,把脚本里的yum
改成apt
即可。
各依赖库的版本请看url里的数字。有升级的话,改一下版本数字即可继续用这个脚本。
脚本
说明在注释里:
# 这一步需要root用户来执行
# 需要git来从GitHub上clone brotli。gcc-c++是pcre需要的,不然configure会报错。
yum install -y wget git gcc-c++
# 以下的步骤不需要root权限
# pcre是支持location的正则表达式的。nginx官网文档说了只支持pcre,不支持pcre2
wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz
tar zxvf pcre-8.43.tar.gz
wget http://zlib.net/zlib-1.2.11.tar.gz
tar zxvf zlib-1.2.11.tar.gz
wget http://nginx.org/download/nginx-1.16.0.tar.gz
tar zxvf nginx-1.16.0.tar.gz
wget https://www.openssl.org/source/openssl-1.0.2s.tar.gz
tar zxvf openssl-1.0.2s.tar.gz
# brotli是google发明的数据压缩算法。它有依赖子库
git clone --depth=1 https://github.com/google/ngx_brotli.git
cd ngx_brotli && git submodule update --init && cd ..
cd nginx-1.16.0
# prefix是把nginx安装到哪个目录
./configure \
--prefix=../nginx \
--with-pcre=../pcre-8.43 \
--with-zlib=../zlib-1.2.11 \
--with-openssl=../openssl-1.0.2s \
--add-module=../ngx_brotli \
--user=root \
--group=root \
--with-file-aio \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_sub_module \
--with-http_gzip_static_module \
--with-http_stub_status_module
make install
运行$/nginx/sbin/nginx
即可启动了。实际启用gzip、http2、brotli、ssl还需修改nginx.conf
哦。简单示例:
http {
...
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/json application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
brotli on;
brotli_types text/plain application/javascript application/json application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
server {
...
listen 443 ssl http2;
ssl_certificate /home/fm/local/nginx/ssl/server.crt;
ssl_certificate_key /home/fm/local/nginx/ssl/server.key;
ssl_session_timeout 5m;
...
}
...
}
非root用户监听80和443端口
非root用户运行nginx不能监听1024以下的端口号。如果不想用root账号来启动,可以先这样设置:
# 需要root用户cd到sbin目录中设权限
chown root:root nginx
chmod 755 nginx
chmod u+s nginx
然后非root用户也能启动nginx并监听80端口了。