Nginx returns static json string

foreword

Since I installed nginx last time, I have forwarded all the external development ports of the server through it. It’s so sweet. Recently, I want to add a function to obtain the latest version number. At first, I wanted to write it in the server. Later, I thought about whether it can be directly through nginx What about configuration? After some attempts, it is indeed possible, so that there is no need to write code separately to respond to requests, and it can reduce server resource usage, and the response performance is also very fast.

Modify the configuration file

Let’s change it on the basis of the configuration file in “Record the first installation and configuration of Nginx” last time , and modify the following paragraphproject.conf

server {
    listen       4100;
    server_name  localhost;

    location / {

        proxy_pass http://login_entrance;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

return simple json string

If it is a simple json string, it can be directly written in the configuration file, which is more convenient:

    location /version/en {
        default_type application/json;
        return 200 '{"code":0,  "version":"1.6"}';
    }

return json file content

If there is a lot of json content, it cannot be completely put in the configuration, because nginxthere config bufferis a 4kb size limit, then you can put the json content in the file:

    location /version/cn {
        default_type application/json;
        alias /data/update/cn_version.json;
    }

The combined configuration file becomes:

server {
    listen       4100;
    server_name  localhost;

    location /version/en {
        default_type application/json;
        return 200 '{"code":0,  "version":"1.6"}';
    }
    
    location /version/cn {
        default_type application/json;
        alias /data/update/cn_version.json;
    }

    location / {

        proxy_pass http://login_entrance;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Summarize

  • Through nginx, you can directly configure and return some static text or json information, so that you don’t need to write additional processing logic, and the efficiency is relatively high
  • If there is a lot of data when returning json content, you can save it to a file and directly reference the file name in the configuration file
==>> Anti-climbing link, please do not click, it will explode on the spot, and we will not be responsible for it! <<==

A good man doesn't mention how brave he was back then, but who can understand how lonely he is now, only standing out from the crowd, let him be respectful and respectful.

Guess you like

Origin blog.csdn.net/shihengzhen101/article/details/130353739