The correct way for nginx to configure cross domain CORS support


What are you doing these two daysCool melon cloud online classThe app uses uni app for full-end support. It is now learning and selling. At present, it is an entry point.

When doing H5, it is inevitable to request the backend API across domains. Although there will be no cross domain problem with the built-in browser of hbuilder (this should be handled internally), the built-in browser will get stuck in a moment, resulting in no response from hbuilder and killing the process is useless. You can only restart and repeat it several times. Who will suffer. Later, it was found that using an external browser would not have this problem, but it faced cross domain problems.

Here, nginx is configured to support CORS, so you don’t have to move any code. The correct configuration is as follows:

location ~ \.php$ {

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE' always;
        add_header 'Access-Control-Allow-Headers' '*' always;
        add_header 'Access-Control-Max-Age' 1728000 always;
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        return 204;

    if ($request_method ~* '(GET|POST|DELETE|PUT)') {
        add_header 'Access-Control-Allow-Origin' '*' always;


PS: there are many garbage articles collected, pasted and copied on the Internet, which have not been verified at all. It will waste more time and take you to the pit.

Note: the above configuration is only suitable for the commissioning stage (because the gate is fully open), please adjust the parameters according to the actual situation.