在我的 nGinx 配置中避免重复代码

Ada*_*ram 4 nginx

我有一个启用了 PHP APC 缓存的 Wordpress 网站,我想在其中加密对http://www.domain.com/wp-login.php*和 的所有请求http://www.domain.com/dashboard?action=profile。我想强制与其他所有内容建立未加密的连接。

我可以让它工作,但配置非常丑陋并且被黑客攻击。我的问题是我仍然必须将我想加密的两个字符串传递给 PHP 引擎。必须有更好的方法来做到这一点,而不是重复这么多。

server {
    listen       443;
    ssl     on;
    ssl_certificate /etc/nginx/ssl/new/server.crt;
    ssl_certificate_key /etc/nginx/ssl/new/server.key;

    server_name  www.domain.com domain.com;
    root   /var/www;
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \wp-login.php.* {
        ##Stuff to send requests to the PHP engine here
    }

    location ~ \dashboard?action=profile.* {
        ##Stuff to send requests to the PHP engine here
    }

    location ~ \.php$ {
        ##Stuff to send requests to the PHP engine here 
    }
}

server {
    listen       80;

    server_name  www.domain.com domain.com;
    root   /var/www;
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \wp-login.php.* {
        ##Stuff to send requests to the PHP engine here
    }

    location ~ \dashboard?action=profile.* {
        ##Stuff to send requests to the PHP engine here
    }

    location ~ \.php$ {
        ##Stuff to send requests to the PHP engine here 
    }

    location ~ \dashboard/\?action\=profile$ {
        rewrite ^ https://$http_host$request_uri? permanent;    
    }

    location ~ \wp-login.php.* {
        rewrite ^ https://$http_host$request_uri? permanent;    
    }
}
Run Code Online (Sandbox Code Playgroud)

dan*_*y74 5

为避免位置块中的 nginx 重复,要么使用 nginx 包含或使用嵌套位置块 - 嵌套位置块示例如下...

    location / {
        proxy_pass http://mywebfeservers;
        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        proxy_set_header Host $http_host;
        proxy_set_header X-Request-ID $uuid;
        proxy_set_header Via $via;

        location /aaa {
            # proxy_pass is not inherited, unsure about proxy_http_version
            proxy_pass http://mywebfeservers;
            proxy_http_version 1.1;
            # Prevent caching
            if_modified_since off;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里所有位置都设置了这些不同的标题。只有 /aaa 位置可以防止缓存,但是它仍然使用相同的标头而不重复配置。可悲的是,您必须重复代理传递,因为继承不适用于代理传递指令(出于我不知道的原因)。