通过 Nginx 反向代理来加速 Google Fonts 文件的加载速度,实现更快的页面加载速度。

首先,你需要创建一个文件名为 google_fonts.conf 的配置文件(或者你可以将以下行添加到已有的 Nginx 配置文件中):

location /google-fonts/css/ {
	sub_filter 'fonts.gstatic.com' '$host/google-fonts';
	sub_filter_once off;
	sub_filter_types text/css;
	proxy_set_header Host fonts.googleapis.com;
	proxy_set_header Accept-Encoding '';
	proxy_redirect off;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Scheme $scheme;
	proxy_pass https://fonts.googleapis.com/css;
	
	proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie Vary;
	
	proxy_cache nginx-cache;
	proxy_cache_valid  500 502 503 504 404 10s;
	proxy_cache_valid  200 302 304 365d;
	proxy_cache_key $support_woff2$host$uri$is_args$args;
	add_header X-Proxy-Cache $upstream_cache_status;
	
	expires max;
}

location /google-fonts/css2/ {
	sub_filter 'fonts.gstatic.com' '$host/google-fonts';
	sub_filter_once off;
	sub_filter_types text/css;
	proxy_set_header Host fonts.googleapis.com;
	proxy_set_header Accept-Encoding '';
	proxy_redirect off;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Scheme $scheme;
	proxy_pass https://fonts.googleapis.com/css2;
	
	proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
	
	proxy_cache nginx-cache;
	proxy_cache_valid  500 502 503 504 404 10s;
	proxy_cache_valid  200 302 304 365d;
	proxy_cache_key $support_woff2$host$uri$is_args$args;
	add_header X-Proxy-Cache $upstream_cache_status;
	
	expires max;
}

location /google-fonts/icon/ {
	sub_filter 'fonts.gstatic.com' '$host/google-fonts';
	sub_filter_once off;
	sub_filter_types text/css;
	proxy_set_header Host fonts.googleapis.com;
	proxy_set_header Accept-Encoding '';
	proxy_redirect off;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Scheme $scheme;
	proxy_pass https://fonts.googleapis.com/icon;
	
	proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
	
	proxy_cache nginx-cache;
	proxy_cache_valid  500 502 503 504 404 10s;
	proxy_cache_valid  200 302 304 365d;
	proxy_cache_key $support_woff2$host$uri$is_args$args;
	add_header X-Proxy-Cache $upstream_cache_status;
	
	expires max;
}

location ~ /google-fonts/.+\.(woff2|woff|svg|ttf)$ {
	rewrite  /google-fonts/(.*) /$1 break;
	
	proxy_set_header Host fonts.gstatic.com;
	proxy_redirect off;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Scheme $scheme;
	proxy_pass https://fonts.gstatic.com;
	
	proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
	
	proxy_cache nginx-cache;
	proxy_cache_valid  500 502 503 504 404 10s;
	proxy_cache_valid  200 302 304 365d;
	proxy_cache_key $host$uri$is_args$args;
	add_header X-Proxy-Cache $upstream_cache_status;
	
	expires max;
}

这里“/google-fonts”是虚拟目录的名称,也可以使用任何其他名称,但必须与主站点 URL 路径相同。

然后,将以下行添加到 Nginx 主配置中,以从新配置的 google_fonts.conf 文件加载配置:

http {
	proxy_temp_path /path/to/temp;
	proxy_cache_path /path/to/cache levels=1:2 keys_zone=nginx-cache:256m max_size=5g inactive=365d;
	include /path/to/google_fonts.conf;
    # other directives
}

接下来,测试 Nginx 配置是否正确:

sudo nginx -t

如果没有错误,重新加载 Nginx 以使更改生效:

sudo service nginx reload

最后,该网站中的字体请求现在将从 googleapis.com 转到你的服务器,从而提高字体加载速度。

需要注意的是,此方法应该仅用于使用 Google Fonts 的网站,并需要遵守 Google 的服务条款。

在 Nginx 服务器配置中使用 if 和 else 可以根据不同的请求参数、请求头、请求方法等条件来做出不同的响应。你可以在 server 块中使用 if 和 else 语句,语法如下:

server {
    # Server configuration
    if ($condition) {
        # Condition is true, do something
    }
    else {
        # Condition is not true, do something else
    }
}

在 server 块中使用 if 和 else 与在 location 块中使用 if 和 else 的使用方法相同。需要注意的是,在 Nginx 中 if 语句执行指令时会有一些注意点,建议遵循以下规则:

1. 不要在一条规则中定义多个 if 语句。

2. 避免在 if 块条件中使用不严谨的匹配表达式。

3. 要么在 if 块中只执行内置或者受限制的指令,要么在 if 块之外执行指令。

4. 为了避免与其他指令的冲突,最好使用 Nginx 内置的指令或支持的模块。

需要注意的是,在 server 块中使用的 if 语句无法与一些指令一起使用,例如 rewrite、return 和 try_files 等指令不支持使用 if 语句。

如果你想判断 nginx 的请求 URL 是否包含指定的参数,可以使用以下步骤:

1. 使用 $request_uri 变量来获取请求 URL,例如:

location /example { if ($request_uri ~* "param=value") { return 200; } }

这将匹配所有包含 param=value 参数的 URL。 ~* 用于指定不区分大小写的匹配。如果需要区分大小写,则使用单个 ~。

2. 使用 $args 变量来获取请求参数,例如:

location /example { if ($args ~* "param=value") { return 200; } }

这将匹配所有包含名为 param 值为 value 的参数的 URL。

上述例子中的 location /example 可以替换为任何你需要匹配的路径,例如 /api/v1。请确保将上述代码插入到正确的 nginx 配置文件中(例如 /etc/nginx/nginx.conf)的正确位置(例如在 server 或 location 块中)。

Nginx 可以采用以下几种方式来防止被 CC(DDoS 攻击):

1. 限制连接速率:可以通过 ngx_http_limit_conn_module 和 ngx_http_limit_req_module 模块限制每个 IP 的连接速率和请求速率,以确保服务器的连接和请求资源分配公平。

2. 过滤恶意请求:可以通过 ngx_http_access_module 模块进行黑白名单控制,阻止恶意请求来自黑名单 IP,减轻服务器的压力。在此基础上可以使用 ngx_http_referer_module 模块进行防盗链。

3. 控制请求大小:可以使用 ngx_http_request_limit_zone_module 和 ngx_http_client_body_module 模块来限制请求大小,防止非法的大量数据提交。

4. 开启缓存:建立服务器缓存来避免过多的请求将达到后端服务器,可以使用 ngx_http_proxy_module 和 ngx_http_fastcgi_module 模块来提高网站的访问速度,同时缓存能够帮助减轻服务器压力并防止被 CC 攻击。

5. 配置 Keep-Alive:启动 keep-alive 功能可以让浏览器和服务器之间的TCP连接保持长连接,有效减轻服务器压力同时提高访问速度。可以使用 ngx_http_headers_module 模块来配置 keep-alive 功能。

6. 使用专业的防火墙及负载均衡:在高访问量的情况下,使用专业的防火墙及负载均衡设备,将请求分配到不同服务器上,提高服务器性能,同时可以在防火墙上进行过滤非法IP,增强安全性。

这些方法可以有效地增强 Nginx 的安全性,更好地防止 CC(DDoS 攻击)和其他安全问题。

以下是所有可用的 Nginx 编译参数列表:

--prefix=path                : 安装路径,默认为 /usr/local/nginx。
--sbin-path=path             : nginx 可执行文件的路径,默认为 prefix/sbin/nginx。
--conf-path=path             : nginx 配置文件的路径,默认为 prefix/conf/nginx.conf。
--error-log-path=path        : 错误日志文件的路径,默认为 prefix/logs/error.log。
--pid-path=path              : nginx 主进程 PID 文件的路径,默认为 prefix/logs/nginx.pid。
--lock-path=path             : nginx 锁文件的路径,默认为 prefix/logs/nginx.lock。
--user=name                  : 指定运行 nginx 的用户,默认为 nobody。
--group=name                 : 指定运行 nginx 的用户组,默认为 nobody。
--build=name                 : 指定编译环境,默认为当前主机的信息。
--builddir=path              : 指定编译时生成临时文件的目录,默认为 /tmp/nginx。
--with-select_module         : 启用 select 模块。
--without-select_module      : 禁用 select 模块。
--with-poll_module           : 启用 poll 模块。
--without-poll_module        : 禁用 poll 模块。
--with-threads               : 启用线程池。
--without-threads            : 禁用线程池。
--with-file-aio              : 启用文件异步 IO。
--with-http_ssl_module       : 启用 SSL/TLS 支持。
--without-http_ssl_module    : 禁用 SSL/TLS 支持。
--with-http_v2_module        : 启用 HTTP/2 支持。
--without-http_v2_module     : 禁用 HTTP/2 支持。
--with-http_realip_module    : 启用 realip 模块,用于获取真实客户端 IP。
--without-http_realip_module : 禁用 realip 模块。
--with-http_addition_module  : 启用 addition 模块,用于添加响应体。
--without-http_addition_module: 禁用 addition 模块。
--with-http_sub_module       : 启用 sub 模块,用于替换响应体。
--without-http_sub_module    : 禁用 sub 模块。
--with-http_dav_module       : 启用 dav 模块,用于 WebDAV 支持。
--without-http_dav_module    : 禁用 dav 模块。
--with-http_flv_module       : 启用 flv 模块,用于流媒体服务器。
--without-http_flv_module    : 禁用 flv 模块。
--with-http_mp4_module       : 启用 mp4 模块,用于流媒体服务器。
--without-http_mp4_module    : 禁用 mp4 模块。
--with-http_gunzip_module    : 启用 gunzip 模块,用于动态解压缩响应体。
--without-http_gunzip_module : 禁用 gunzip 模块。
--with-http_gzip_static_module : 启用 gzip_static 模块,用于预压缩静态文件。
--without-http_gzip_static_module : 禁用

使用 NGINX 官方源安装,启动程序发现 Systemd 中存在报错:Can't open PID file /var/run/nginx.pid (yet?) after start: No such file or directory

● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-12-10 03:35:04 MSK; 8s ago
     Docs: http://nginx.org/en/docs/
  Process: 9226 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 9229 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 9230 (nginx)
   CGroup: /system.slice/nginx.service
           ├─9230 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─9231 nginx: worker process

Dec 10 03:35:04 vm228965.u83712.kvm.centos.7.64 systemd[1]: Stopped nginx - high performance web server.
Dec 10 03:35:04 vm228965.u83712.kvm.centos.7.64 systemd[1]: Starting nginx - high performance web server...
Dec 10 03:35:04 vm228965.u83712.kvm.centos.7.64 systemd[1]: Can't open PID file /var/run/nginx.pid (yet?) after start: No such file or directory
Dec 10 03:35:04 vm228965.u83712.kvm.centos.7.64 systemd[1]: Started nginx - high performance web server.

原因是Nginx 启动时 PID 文件并未生成,导致文件无法读取

知道问题如何产生,自然就有了解决办法。在 /usr/lib/systemd/system/nginx.service 中添加如下语句即可,作用是在执行可执行文件前等待 0.1s 。

ExecStartPost=/bin/sleep 0.1

添加后 /usr/lib/systemd/system/nginx.service 如下:

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPost=/bin/sleep 0.1
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

然后重新加载配置、启动

systemctl daemon-reload
systemctl restart nginx

问题修复。

Nginx 利用 IP2Locaion 模块实现地区负载均衡和IP定位。

由于GeoIP2的效率实在是“惊人”,和那“高到爆”的识别精度,真是让人想爆粗口。经过权衡,将IP定位模块更换为 IP2Locaion。

如果还没安装 IP2Location C Library,请先移步到 https://www.24kplus.com/linux/871.html 安装 IP2Location C Library

下载 Nginx IP2Locaion 模块

git clone https://github.com/ip2location/ip2location-nginx.git

查看当前 Nginx 版本信息

nginx -V

可以看到 Nginx 的版本为1.16.0 和 configure 参数,把 configure 参数拷贝保存下来,后面需要用到

到官网 https://nginx.org/en/download.html 找到对应的版本源码下载并解压。本站以1.16.0为例:

下载并解压

wget https://nginx.org/download/nginx-1.16.0.tar.gz
tar -zxf nginx-1.16.0.tar.gz
cd nginx-1.16.0

备用下载地址: https://down.24kplus.com/linux/nginx-1.16.0.tar.gz

生成新的 nginx

把刚刚复制的 configure 参数粘贴到 ./configure 后面, 在结尾处加入 -–add-module=../ip2location-nginx

./configure \
--prefix=/etc/nginx \
.....
# 在结尾处加入一行
-–add-module=../ip2location-nginx
# 如果想编译为动态模块,则添加
--add-dynamic-module=../ip2location-nginx
make

编译好之后不要安装, 停止 nginx 服务

systemctl stop nginx

复制编译好的新 nginx 文件拷贝到sbin下

cp /usr/sbin/nginx /usr/sbin/nginx.bak
cp objs/nginx /usr/sbin

编辑 nginx.conf 文件,在 http {} 中加入以下代码:

http {
……
#doc https://github.com/ip2location/ip2location-nginx
# on 为启用,off 为禁用
ip2location on;
#/usr/share/IP2Location/IP2LOCATION-LITE-DB3.BIN 替换成你的 IP2Locaion 数据路径。
ip2location_database /usr/share/IP2Location/IP2LOCATION-LITE-DB3.BIN;
# 可选参数 ip2location_access_type file_io|shared_memory|cache_memory
# 默认为 shared_memory
# 建议不要选择 file_io, 否则可能会严重拖慢响应速度。
ip2location_access_type shared_memory
……
}

官方提供免费版BIN文件下载: https://lite.ip2location.com/ip2location-lite ,根据自己的需要下载对应版本。

编辑 fastcgi_params 文件,在结尾加入以下几行代码(可选):

#IP2Location, with ip2location on;
fastcgi_param  IP_COUNTRY_CODE		$ip2location_country_short;
fastcgi_param  IP_COUNTRY_NAME		$ip2location_country_long;
fastcgi_param  IP_REGION_NAME		$ip2location_region;
fastcgi_param  IP_CITY_NAME  		$ip2location_city;

更多参数查考官方文档:https://github.com/ip2location/ip2location-nginx

启动 nginx 服务

systemctl start nginx

在 phpinfo 信息中可以看到:

当然,也可以在 nginx 中直接使用 $ip2location_country_short,$ip2location_region等变量来实现地区负载均衡。

IP2Location C Library

1、下载并解压

wget -O IP2Location-C-Library-8.0.8.tar.gz https://codeload.github.com/chrislim2888/IP2Location-C-Library/tar.gz/8.0.8
tar -zxf IP2Location-C-Library-8.0.8.tar.gz
cd IP2Location-C-Library-8.0.8

备用下载地址:https://down.24kplus.com/linux/IP2Location-C-Library-8.0.8.tar.gz

2、编译安装

autoreconf -i -v --force
./configure --prefix=/usr
make
make install
cd data
perl ip-country.pl

如果出现错误

configure.ac:42: error: possibly undefined macro: AC_PROG_LIBTOOL
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.

执行:

yum install libtool libsysfs

3、测试(可选)

cd test
./test-IP2Location

IP2Location API version: 8.0.8 (80008)
IP2Location IPv4 Testing passed.
IP2Location IPv6 Testing passed.

Welcome to nginx!

安装

1、准备编译环境

yum -y install libxml2 libxml2-devel libxslt-devel gd-devel gperftools libuuid-devel libblkid-devel libudev-devel fuse-devel libedit-devel libatomic_ops-devel gcc-c++

以及安装 libmaxminddb(如不启用 GeoIP2 模块可以忽略)

2、下载并解压

由于 GeoIP 官方已不再支持,如果要支持最新 GeoIP2 ,需要添加ngx_http_geoip2_module。下载 GeoIP2 模块

git clone https://github.com/leev/ngx_http_geoip2_module.git

下载,解压

wget https://nginx.org/download/nginx-1.16.0.tar.gz
tar -xvf nginx-1.16.0.tar.gz
cd nginx-1.16.0

3、配置并构建 Nginx

./configure \
--prefix=/usr/local \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib64/nginx/modules \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--user=nginx \
--group=nginx \
--with-select_module \
--with-poll_module \
--with-threads \
--with-file-aio \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_xslt_module \
--with-http_xslt_module=dynamic \
--with-http_image_filter_module \
--with-http_image_filter_module=dynamic \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_auth_request_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_degradation_module \
--with-http_slice_module \
--with-http_stub_status_module \
--with-mail \
--with-mail=dynamic \
--with-mail_ssl_module \
--with-stream \
--with-stream=dynamic \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-stream_ssl_preread_module \
--with-google_perftools_module \
--with-cpp_test_module \
--with-compat \
--with-pcre \
--with-pcre-jit \
--with-libatomic \
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' \
--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' \
--add-dynamic-module=../ngx_http_geoip2_module
make
sudo make install

查看 Nginx 是否安装成功

nginx -v

nginx version: nginx/1.16.0

4、创建 nginx 用户

groupadd nginx
useradd -g nginx nginx

5、创建 nginx cache 文件夹

mkdir /var/cache/nginx

6、配置 nginx.service

sudo vi /usr/lib/systemd/system/nginx.service

复制粘贴:

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

7、启用 GeoIP2 模块(可选)

编辑 /etc/nginx/nginx.conf 文件

在 events 之前加入:

load_module /usr/lib64/nginx/modules/ngx_http_geoip2_module.so;

在 http 内加入以下代码:

#/usr/share/GeoIP/GeoIP2-Country.mmdb 替换为实际路径
geoip2 /usr/share/GeoIP/GeoIP2-Country.mmdb {
    auto_reload 60m;
    $geoip2_metadata_country_build metadata build_epoch;
    $geoip2_data_country_code country iso_code;
    $geoip2_data_country_name country names en;
}

#/usr/share/GeoIP/GeoIP2-City.mmdb 替换为实际路径
geoip2 /usr/share/GeoIP/GeoIP2-City.mmdb {
    auto_reload 60m;
    $geoip2_data_city_name city names en;
}

fastcgi_param COUNTRY_CODE $geoip2_data_country_code;
fastcgi_param COUNTRY_NAME $geoip2_data_country_name;
fastcgi_param CITY_NAME    $geoip2_data_city_name;

8、启动 nginx 服务

systemctl start nginx
systemctl enable nginx

前言

HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer 或 Hypertext Transfer Protocol Secure,超文本传输安全协议),是以安全为目标的HTTP通道,简单讲是HTTP的安全版。

申请免费ssl证书的方式有很多,这里就不再多说。

1、在站点配置 server { } 中加入以下代码

#监听ssl默认端口443
#ipv4
listen 443 ssl;
#如果支持ipv6
listen [::]:443 ssl;
	
#注意:这里24kplus.com替换成你的证书名字
ssl_certificate  ssl/24kplus.com.pem;
ssl_certificate_key ssl/24kplus.com.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

2、重启ningx

systemctl restart nginx

启用ssl就这么简单!

nginx https

免费SSL证书申请直达航班:

阿里云 https://cn.aliyun.com/product/cas