AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 716215
Accepted
Naftuli Kay
Naftuli Kay
Asked: 2015-08-24 21:58:39 +0800 CST2015-08-24 21:58:39 +0800 CST 2015-08-24 21:58:39 +0800 CST

Vários diretórios de arquivos estáticos, servidor PHP FPM único

  • 772

Eu tenho dois diretórios dos quais preciso servir ativos estáticos:

  1. /srv/web: recursos estáticos que incluem imagens, JavaScript, HTML etc.
  2. /srv/php: Scripts PHP dinâmicos juntamente com alguns ativos estáticos.

Estou usando o NGINX e configurei assim:

server {
    listen 80;
    server_name _;

    # root /;
    index index.php index.html index.htm;
    try_files /srv/web/$uri /srv/php/$uri =404;

    location ~ \.php$ {
        root /srv/php;
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
#       fastcgi_param SCRIPT_FILENAME /srv/php$fastcgi_script_name;
        include fastcgi_params;
    }
}

Estou no Ubuntu 14.04, a versão do pacote PHP FPM é 5.5.9, a versão do pacote NGINX é 1.4.6.

O objetivo simples aqui é servir arquivos estáticos de /srv/webprimeiro, caso contrário /srv/php, retorne 404. Todos os arquivos que terminam em \.php$serão solicitados do PHP FPM pelo soquete Unix, e isso está funcionando.

O problema que estou tendo atualmente é que a indexdiretiva sobre o servernão está funcionando como planejado. Eu tenho um index.htmlarquivo em /srv/web, e quando eu faço

curl -is http://localhost/

Eu recebo um 404.

Esta é a maneira mais ideal de configurar um site NGINX com várias pastas de sistema de arquivos para servir ao lado do PHP? Alguma ideia de por que meu índice estático não está funcionando?


Atualizar

De acordo com a resposta do AD7six abaixo, atualizei minha configuração para ficar assim:

server {
    listen 80;
    server_name _; # listen at all host names

    # serve static files first from /srv/web, then from /srv/php, and any dynamic PHP files from
    # FastCGI/FPM at the Unix socket.
    location / {
        root /srv/web;
        index index.html index.htm;
        try_files $uri $uri/ @php;
    }

    location @php {
        root /srv/php;
        index index.php;
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        root /srv/php;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/php/$fastcgi_script_name;
        include fastcgi_params;
    }
}

Minha listagem de diretórios é assim:

/srv/
|-- php
|   |-- demo.php
|   |-- index.php
|   `-- phpstatic.txt
`-- web
    |-- static.html
    `-- subdir
        `-- index.html

3 directories, 5 files

Obter arquivos estáticos e arquivos PHP funciona conforme planejado e obter /subdir/com seu índice funciona bem, mas se eu GET /, recebo um 403 proibido e o nginx reclama da listagem de diretórios:

2015/08/24 21:50:59 [error] 9159#0: *7 directory index of "/srv/web/" is forbidden, client: 127.0.0.1, server: _, request: "GET / HTTP/1.1", host: "localhost"

Não sei por que isso está falhando, mas pelo menos cheira a progresso.

nginx
  • 1 1 respostas
  • 2683 Views

1 respostas

  • Voted
  1. Best Answer
    AD7six
    2015-08-25T00:31:21+08:002015-08-25T00:31:21+08:00

    Múltiplas raízes não funcionarão assim

    Com esta configuração:

    server {
        # root /;
        index index.php index.html index.htm;
        try_files /srv/web/$uri /srv/php/$uri =404;
    

    Não há nenhum processamento de solicitação que usaria a diretiva index, conforme escrito, a solicitação deve corresponder a um arquivo. Usar o log de depuração confirma isso:

    2015/08/24 08:12:11 [debug] 17173#0: *26 try files phase: 13
    2015/08/24 08:12:11 [debug] 17173#0: *26 http script copy: "/srv/web/"
    2015/08/24 08:12:11 [debug] 17173#0: *26 http script var: "/"
    2015/08/24 08:12:11 [debug] 17173#0: *26 trying to use file: "/srv/web//" "/srv/web//"
    2015/08/24 08:12:11 [debug] 17173#0: *26 http script copy: "/srv/php/"
    2015/08/24 08:12:11 [debug] 17173#0: *26 http script var: "/"
    2015/08/24 08:12:11 [debug] 17173#0: *26 trying to use file: "/srv/php//" "/srv/php//"
    2015/08/24 08:12:11 [debug] 17173#0: *26 trying to use file: "=404" "=404"
    

    Usando uma try_filesdiretiva que procura diretórios como este:

    try_files /srv/web/$uri /srv/web/uri/ /srv/php/$uri /srv/php/$uri/ =404;
    

    também não funciona:

    2015/08/24 08:16:17 [debug] 17651#0: *33 http script copy: "/srv/web/"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script var: "/srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 trying to use file: "/srv/web//srv/web//index.html" "/srv/web//srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script copy: "/srv/web/"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script var: "/srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 trying to use dir: "/srv/web//srv/web//index.html" "/srv/web//srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script copy: "/srv/php/"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script var: "/srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 trying to use file: "/srv/php//srv/web//index.html" "/srv/php//srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script copy: "/srv/php/"
    2015/08/24 08:16:17 [debug] 17651#0: *33 http script var: "/srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 trying to use dir: "/srv/php//srv/web//index.html" "/srv/php//srv/web//index.html"
    2015/08/24 08:16:17 [debug] 17651#0: *33 trying to use file: "=404" "=404"
    

    Observe que a "raiz" está confusa, try_filesespera uma url e não um caminho de arquivo. Sugiro não continuar tentando usar uma solução desse tipo - especialmente não definindo o root como /e potencialmente permitindo o acesso a qualquer arquivo no servidor.

    Use dois blocos de localização

    Em vez disso, mantenha as coisas simples. Esta configuração servirá todo o conteúdo estático:

        root /srv/web;
        index index.html;
        try_files $uri $uri/;
    

    Esta configuração serve todo o conteúdo php:

        root /srv/php;
        index index.php;
        try_files $uri $uri/;
    

    Basta juntá-los:

    location / {
        root /srv/web;
        index index.html;
        try_files $uri $uri/ @php;
        error_page 403 = @php; # see note below
    }
    
    location @php {
        root /srv/php;
        index index.php;
        try_files $uri $uri/ =404;
    }
    
    location ~ \.php$ {
        # as before
    }
    

    Uma pegadinha é que, com esse tipo de configuração, uma solicitação que corresponda a uma pasta na /srv/webqual não haja um index.htmlarquivo gerará um erro 403 (já que a solicitação é para um diretório e não há arquivo de índice de diretório). Para permitir que essas solicitações também sejam tratadas pelo php - é necessário redirecionar os erros 403 para o manipulador do php.

    • 2

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve