Search code examples
nginxhttp-referernginx-location

Nginx unknown directive "if"


On my Nginx server, in order to save time, I made etc/nginx/include.conf and put this line in etc/nginx/sites-available/site1.conf:

location / {
    include /etc/nginx/include.conf;
    try_files $uri $uri/ /index.php?page=$uri;
}

The content of include.conf :

if ($http_referer ~* (badreferers)) { 
        return 403; 
}

When testing the conf file, this error emerges: [emerg] unknown directive "if" in /etc/nginx/include.conf:1

When I put the if statement directly in etc/nginx/sites-available/site1.conf, it doesn't give an error.

What could be wrong here?

Update: nginx -V gives:

nginx version: nginx/1.4.6 (Ubuntu) built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) TLS SNI support enabled configure arguments: --with-cc-opt='-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_spdy_module --with-http_sub_module --with-http_xslt_module --with-mail --with-mail_ssl_module


Solution

  • You use old nginx version 1.4. On modern 1.10.2 your config works fine.

    I've checked the sources of nginx. The "include" directive isn't just replaced with content of included file. It is processed differently depending on context. So there are definitely some restrictions of what you may put in included file. At least in your nginx version. As nginx documentation says

    Included files should consist of syntactically correct directives and blocks.