programing

Nginx는 .php 파일을 실행하는 대신 다운로드로 제공합니다.

sourcejob 2022. 9. 22. 00:16
반응형

Nginx는 .php 파일을 실행하는 대신 다운로드로 제공합니다.

액체(Digital Ocean)에 웹사이트를 설치하고 있습니다.NGINX와 PHP를 올바르게 설치하는 데 문제가 있습니다.https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04 튜토리얼을 했는데 .timeout 파일을 실행하려고 하면 다운로드만 되고...예를 들어... http://5.101.99.123/info.php★★★★★★★★★★★★...으로 http://5.101.99.123인덱스를

감 잡히는 게 없어요?

-rw-r--r--  1 agitar_user www-data   418 Jul 31 18:27 index.php
-rw-r--r--  1 agitar_user www-data    21 Aug 31 11:20 info.php

/etc/nginx/sites-available/default

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www/html;
        index index.html index.htm index.php;

        # Make site accessible from http://localhost/
        server_name agitarycompartir.com;

               location ~ \.php$ {
                    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    ## NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #
    #               # With php5-cgi alone:
    #               fastcgi_pass 127.0.0.1:9000;
    #               # With php5-fpm:
                    fastcgi_pass unix:/var/run/php5-fpm.sock;
                    fastcgi_index index.php;
                    include fastcgi_params;
            }
  

              location / {
                    
                    try_files $uri $uri/ =404;
                    # Uncomment to enable naxsi on this location
                    # include /etc/nginx/naxsi.rules
            }

...

다른 "위치"는 코멘트...

.

이것을 시험해 보세요.

  1. ★★/etc/nginx/sites-available/default

  2. nginx 가 포토 80 IPv4 및 IPv6 로 리슨 하도록, 양쪽의 리슨 회선을 언코멘트 합니다.

     listen   80; ## listen for ipv4; this line is default and implied
     listen   [::]:80 default_server ipv6only=on; ## listen for ipv6
    
  3. ★★를 남기다server_name

     # Make site accessible (...)
     server_name localhost;
    
  4. index.phpindex 표시

     root /usr/share/nginx/www;
     index index.php index.html index.htm;
    
  5. ★★★★location ~ \.php$ {}

     # pass the PHP scripts to FastCGI server listening on (...)
     #
     location ~ \.php$ {
             try_files $uri =404;
             fastcgi_split_path_info ^(.+?\.php)(/.+)?$;
             # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    
             # With php5-cgi alone:
             #fastcgi_pass 127.0.0.1:9000;
             # With php5-fpm:
             fastcgi_pass unix:/var/run/php5-fpm.sock;
             fastcgi_index index.php;
             include fastcgi_params;
     }
    
  6. ★★/etc/php5/fpm/php.ini 꼭 해 주세요.cgi.fix_pathinfo로 설정되어 있다.0

  7. 와 nginx 를 합니다.sudo service nginx restart && sudo service php5-fpm restart


저는 일주일 전에 Linux를 사용하기 시작했기 때문에, 꼭 도움이 되었으면 합니다.파일을 편집하기 위해 나노 텍스트 에디터를 사용하고 있습니다.nano가 없으면 apt-get install nano를 실행합니다.자세한 내용은 구글에서 확인하세요.

브라우저 캐시를 비우는 것으로 해결된 유사한 문제가 있었습니다(다른 브라우저에서도 정상적으로 동작했습니다).

Nginx 서버에서 php 파일을 실행하려면 /etc/nginx/sites-enabled/default에 추가해야 합니다.

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

위의 많은 솔루션과 올바르게 동작하는 솔루션이 있습니다만, 그 기능을 이해하지 못하고, 코드, 특히 fastcgi를 카피 페이스트 하는 것만으로 고민하고 있었습니다.여기 내 2센트야

  1. nginx는 웹 서버(애플리케이션서버는 아님)이므로 정적 페이지만 처리할 수 있습니다.
  2. 예를 들어 index.filength, nginx는 .filength 파일을 렌더링/삭제하려고 시도합니다.이것은 .filength 파일(또는 정적 파일인 .filength, .filength 등 선택된 몇 개의 확장자를 제외하고)을 이해할 수 없기 때문입니다.
  3. 따라서 다른 종류의 파일을 실행하기 위해서는 nginx와 어플리케이션(여기서는 php 어플리케이션) 사이에 있는 것이 필요합니다.여기서 Common Gateway Interface(CGI; 공통 게이트웨이 인터페이스)가 사용됩니다.이 통신을 관리하는 소프트웨어입니다.CGI는 가능한 모든 언어 Python(uWSGI), PHP(FPM), 그리고 C로 구현될 수 있습니다.Fast CGI는 기본적으로 CGI의 업그레이드 버전으로 CGI보다 훨씬 빠릅니다.

Apache와 같은 일부 서버에서는 PHP 해석에 대한 지원이 내장되어 있기 때문에 CGI가 필요하지 않습니다.

이 디지털 오션 링크는 FPM을 설치하는 절차를 잘 설명하고 있으며, 다른 쪽에서는 IMHO에 매우 잘 응답하기 때문에 렌더링 대신 php 파일이 다운로드되는 문제를 해결하기 위해 필요한 단계를 기술하고 있지 않습니다.

nginx config /etc/nginx/sites-available/default 또는 구성 파일을 업데이트합니다.

php7을 사용하고 있는 경우는, 이것을 사용해 주세요.

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;      
    }

php5 를 사용하고 있는 경우는, 이것을 사용해 주세요.

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

자세한 내용은 여기를 참조하십시오.자세한 내용은 이쪽

저도 같은 문제가 있었는데 어떤 대답도 문제를 해결하지 못했어요.

실행:

sudo nginx -t

/etc/nginx/syslog-available/default로 컨피규레이션파일을 테스트합니다.

다음과 같은 오류가 발생했습니다.

nginx: [emerg] unexpected end of file, expecting "}" in /etc/nginx/sites-enabled/default:115
nginx: configuration file /etc/nginx/nginx.conf test failed

그래서 컨피규레이션파일에 들어가서 마지막 줄에

#}

코멘트 없이 테스트 명령을 다시 실행했더니 작동했습니다.

이건 나한테 효과가 있었어.

1) MyApp 파일

vi /etc/nginx/sites-available/myApp

server {
  listen 80;
  listen [::]:80;

  root /var/www/myApp;
  index index.php index.html index.htm;

  location ~ \.php$ {
      try_files $uri =404;
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass unix:/run/php/php7.0-fpm.sock;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
      }
}

PHP5 사용자

바꾸다

fastcgi_pass unix:/run/php/php7.0-fpm.sock;

로.

fastcgi_pass unix:/var/run/php5-fpm.sock;

2) cgi를 설정합니다.fix_pathinfo

cgi를 설정합니다.fix_pathinfo를 0으로 설정합니다.

장소:

PHP5 /etc/php5/fpm/php.ini

PHP7 /etc/php/7.0/fpm/php.ini


3) 서비스의 재기

FPM

php5sudo service php5-fpm restart

php7sudo service php7.0-fpm restart

NGINX

sudo service nginx restart

이 보탬이 .?$query_string/index.로 하다

location / {
        try_files $uri $uri/ /index.php?$query_string;
}
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html;
    index index.php index.html index.htm;

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

위의 스니펫은 php7.2의 경우 나에게 효과가 있었습니다.

제안된 답변 중 하나라도 제대로 작동하지 않는 경우 다음을 수행하십시오.

1. etc/syslog5/fpm/pool.d에서 www.conf를 수정합니다.

listen = 127.0.0.1:9000;(delete all line contain listen= )

2. usr/local/nginx/conf에서 nginx.conf를 수정합니다.

remove server block server{} (if exist) in block html{} because we use server{} in default (config file in etc/nginx/site-available) which was included in nginx.conf.

3. etc/nginx/site-available에서 기본 파일 수정

location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; }

4.nginx 서비스

sudo 서비스 nginx 재시작

5.120 php 서비스

서비스 php5-fpm 재시작

6. 삭제

/usr/share/nginx/html에 php 파일을 만들고 "server_name/file_name.php"에서 실행합니다(server_name은 설정에 따라 다르며, normaly는 localhost, file_name).php는 /usr/share/nginx/filename 에서 작성된 파일 이름입니다.

Ubuntu 14.04를 사용하고 있습니다.

위의 답변은 제가 도달한 해결책에 대해 너무 많은 코멘트를 하는 것 같습니다.내 파일은 다음과 같습니다.

/etc/nginx/syslog-available/default

location ~ \.php$ {
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}

이것이 일요일 오후에 좌절하는 사람들에게 도움이 되기를 바랍니다(c:

PHP 7과 같은 문제가 있는 사람을 위해, 이것이 nginx가 Cent에서 php 파일을 올바르게 실행하도록 하기 위해 제가 한 일입니다.OS 7은 여기에 게재되어 있기 때문에, 같은 문제를 안고 있는 유저가 있는 경우:

  • Digital Ocean에 관한 이 문서를 단계별로 살펴보십시오.

  • 를 엽니다./etc/nginx/conf.d/default.conf(디폴트로는 사이트도 사용할 수 있는 사이트도 없기 때문에 그에 따라 편집할 수 있습니다).

  • 를 편집하다location파라미터는 다음과 같습니다.

default.conf:

location ~ \.php$ {
    try_files $uri =404;
    #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;

    #instruct nginx execute php7 files instead download them :D
    fastcgi_pass unix:/var/run/php-fpm/www.sock;

    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}
  • Nginx 및 PHP 서비스 재시작sudo systemctl restart php-fpm그리고.sudo systemctl restart nginx.

  • 마지막이지만 가장 중요한 것은 브라우저 캐시 클리어 또는 실행 중incognito (Chrome)또는Private Browsing (Firefox)기타...

도움이 되고 행복한 코딩이 되길 바랍니다.

제 해결책은 다음과 같이 추가하는 것이었습니다.

    location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

커스텀 컨피규레이션파일로 이행합니다.etc/nginx/sites-available/example.com.conf

에 추가/etc/nginx/sites-available/default나한테는 통하지 않았어

사용하지 않는 케이스입니다./etc/nginx/sites-available/default다른 서버 블록컨피규레이션파일(example.com 등)을 사용하고 있었는데 이 문제를 해결할 수 있는 유일한 방법은 기본 서버 블록컨피규레이션파일 심볼릭링크를 삭제하는 것입니다.

$ rm /etc/nginx/sites-enabled/default

Nginx를 다시 로드합니다.

$ sudo systemctl reload nginx

이게 결국 제 경우엔 범인이 다시 쓰는 규칙으로 통했던 겁니다
nginx rewrite 규칙을 다음과 같이 변경하였습니다.

   location /vendors { rewrite ^/vendors/?$ /vendors.php break; } 

...가 된다.

  location /vendors { rewrite ^/vendors/?$ /vendors.php last; }

마지막 키워드를 지정하지 않으면 요청은 재시작되지 않았기 때문에.php로케이션 세그먼트(segment)를 다운로드로 해석했습니다.

이 코드로 문제를 해결했습니다(IP 변경).

location / {
access_log off;
    log_not_found  off;
    client_max_body_size    2000m;
    client_body_buffer_size 512k;
    proxy_buffering on;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    proxy_buffer_size 64k;
    proxy_buffers 32 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_connect_timeout 300s;
    proxy_http_version 1.1;
    proxy_set_header Range "";
    proxy_pass   https://123.123.123.123:444;
    proxy_set_header   Host   $host;
    proxy_set_header   X-Real-IP  $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_redirect     off;
}

참고로, 나는 내 php-fpm이 실행되고 있지 않다는 것을 발견했고, 나는 그것을 다음과 같이 수정했다.service php7.2-fpm start.

Ubuntu 16.04와 php7에서 나에게 효과가 있었던 것은 이 행을 삭제하는 것이었다.

fastcgi_split_path_info ^(.+\.php)(/.+)$;

그 후 php 파일 다운로드가 중지되었습니다.

/etc/nginx/sites-available/default의 .php 위치를 주석 해제합니다.

sudo vi /etc/nginx/sudo-available/default:

location ~ \.php$ {
            include snippets/fastcgi-php.conf;

            # With php5-cgi alone:
    #       fastcgi_pass 127.0.0.1:9000;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

다른 게 도움이 안 된다면요이전에 info.php 테스트 파일을 사용하여 apache2를 설치했을 수도 있습니다.localhost의 App Data(캐시, cookie)를 클리어하기만 하면 됩니다.

nginx 설정 파일의 확장자가 *.conf 인 것을 확인합니다.
예: /etc/nginx/conf.d/myfoo.conf

저도 같은 상황이에요.컨피규레이션파일의 이름을 myfoo에서 myfoo.conf로 바꾸면 수정되었습니다.nginx의 이름을 변경한 후 재시작하는 것을 잊지 마십시오.

먼저 해야 합니다.Remove cache브라우저에

그런 다음 터미널을 열고 다음 명령을 실행합니다.

sudo apt-get install php-gettext
sudo nano /etc/nginx/sites-available/default

다음으로 다음 코드를 추가합니다.default파일:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

불일치가 있는 경우 수정만 하고 다음 명령을 사용하여 단말기에서 Nginx를 재시작합니다.

sudo systemctl restart nginx

그런 다음 브라우저로 이동하여 즐기십시오.

저에게는 fastcgi_pass unix:/var/run/php5-fpm.sock 행이었습니다.

fastcgi_pass unix:/run/fpm.disc;

저는 이 문제를 해결하기 위해 미칠 것 같았습니다. 문제는 Cloudflare가 php 파일을 캐시하고 계속 다운로드하도록 했다는 것입니다.

제가 해결한 건 Cloudflare의 캐시를 삭제하는 거였어요

이 문제를 해결한 것은 css가 로딩되지 않는 문제가 있는 경우 이 서버 블록도 다른 로케이션 블록 위에 있다는 것입니다.내 사이트 컨피규레이션파일에 추가했어

location ~ [^/]\.php(/|$) {
fastcgi_split_path_info  ^(.+\.php)(/.+)$;
fastcgi_index            index.php;
fastcgi_pass             unix:/var/run/php/php7.3-fpm.sock;
include                  fastcgi_params;
fastcgi_param   PATH_INFO       $fastcgi_path_info;
fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

한 가지 더 확인해야 할 것은 PHP를 설정하기 전에 HTTPS 액세스를 설정한 경우(certbot을 사용), 2개의 서버 블록이 있기 때문에 /etc/nginx/sites-available/default에서 변경을 두 번 해야 합니다(포트 80에서 리슨, 포트 443에서 리슨).

(이 서버를 주로 이메일용으로 셋업하고 있었습니다.처음 nginx를 설치했을 때는 certbot을 보다 쉽게 실행하기 위한 방법으로 PHP를 사용할 수 없었습니다.)

저는 오랫동안 이 문제에 대해 고민하고 있었고, 이 절차들은 제게 효과가 있었습니다.

1단계: 모든 PHP 파일의 위치 블록 구성

location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
}

스텝 2: 설정 파일에 fastcgi_param 추가 /etc/nginx/fastcgi_params 파일을 열고 파일 끝에 다음 행을 추가하면 됩니다.

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;

그런 다음 서비스를 다시 시작합니다.

systemctl restart php7.3-fpm
systemctl restart nginx

php-fpm 서비스가 실행되지 않은 경우 Mac에 homebrew와 함께 PHP를 설치했습니다.

brew services list

여기에 이미지 설명 입력

서비스를 시작하여 php 스크립트 실행을 시작합니다.

brew services start php

nginx 서버 위치 블록의 내 fastcgi 설정

location ~ \.php$ {
  ...
  include        fastcgi_params;
  fastcgi_pass   127.0.0.1:9000;
  ...
}

브라우저 캐시를 비운 것이 효과가 있었습니다.

언급URL : https://stackoverflow.com/questions/25591040/nginx-serves-php-files-as-downloads-instead-of-executing-them

반응형