You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx配置文件中if条件内$scheme与$host如何拼接?

Fixing Nginx Variable Concatenation in if Conditions

Hey there, I get why you tried that approach, but Nginx doesn’t support directly concatenating variables like $scheme://$host inside an if condition— that’s exactly why your rule isn’t taking effect. Let’s fix this properly.

The Correct Way to Concatenate Variables

Nginx requires you to first store the concatenated result in a new variable using the set directive, then use that variable in your if check. Here’s how to adjust your config:

server {
    # Your existing listen/server_name directives here
    listen 80;
    server_name example.com;

    # Step 1: Create a variable with the concatenated scheme + host
    set $full_host "$scheme://$host";

    # Step 2: Use the new variable in the if condition
    if ($full_host = 'http://example.com') {
        return 301 https://example.com$request_uri;
    }

    # Rest of your server config...
}

A More Efficient Alternative

Since your end goal is to redirect HTTP traffic for example.com to HTTPS, you can skip the concatenation entirely and check the conditions separately. This is more straightforward and avoids any variable edge cases:

server {
    listen 80;
    server_name example.com;

    # Directly check if the scheme is HTTP (no need to concatenate)
    if ($scheme = http) {
        return 301 https://$host$request_uri;
    }

    # Rest of your server config...
}

If this server block handles multiple domains and you want to target only example.com, you can use simple nested ifs (note: Nginx discourages complex nested logic, but this basic case is safe):

server {
    listen 80;
    server_name example.com other-domain.com;

    if ($host = example.com) {
        if ($scheme = http) {
            return 301 https://example.com$request_uri;
        }
    }

    # Rest of your server config...
}

Why Your Original Code Failed

Nginx’s if condition parser doesn’t handle inline string concatenation of variables. You can’t combine $scheme, ://, and $host directly in the condition— you need to precompute that value into a variable first with set.

内容的提问来源于stack exchange,提问作者Kevin Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:16:55