# nginx, php and fpm

## iamwill

I am trying to get nginx and php-fpm to play.  I'm hosting a bludit blog and for some reason, I can't get the permissions right because every time I go to the site url, I am getting a 502 Bad Gateway error.  The DDNS is setup and nginx is working because if I remove everything and leave just an index.html, the page loads fine.  Any help on getting this to work right would be great, and thanks in advance.

Here are the usuals:

emerge --info

```
Portage 2.3.5 (python 3.4.5-final-0, hardened/linux/amd64, gcc-5.4.0, glibc-2.23-r3, 4.9.16-gentoo x86_64)

=================================================================

System uname: Linux-4.9.16-gentoo-x86_64-Intel-R-_Core-TM-_i5-6500_CPU_@_3.20GHz-with-gentoo-2.3

KiB Mem:     8055864 total,   7664156 free

KiB Swap:    4194300 total,   4194300 free

Timestamp of repository gentoo: Mon, 15 May 2017 00:45:01 +0000

sh bash 4.3_p48-r1

ld GNU ld (Gentoo 2.26.1 p1.0) 2.26.1

app-shells/bash:          4.3_p48-r1::gentoo

dev-lang/perl:            5.24.1-r1::gentoo

dev-lang/python:          2.7.12::gentoo, 3.4.5::gentoo

dev-util/pkgconfig:       0.28-r2::gentoo

sys-apps/baselayout:      2.3::gentoo

sys-apps/openrc:          0.24.2::gentoo

sys-apps/sandbox:         2.10-r3::gentoo

sys-devel/autoconf:       2.69::gentoo

sys-devel/automake:       1.15-r2::gentoo

sys-devel/binutils:       2.26.1::gentoo

sys-devel/gcc:            5.4.0-r3::gentoo

sys-devel/gcc-config:     1.7.3::gentoo

sys-devel/libtool:        2.4.6-r3::gentoo

sys-devel/make:           4.2.1::gentoo

sys-kernel/linux-headers: 4.4::gentoo (virtual/os-headers)

sys-libs/glibc:           2.23-r3::gentoo

Repositories:

gentoo

    location: /usr/portage

    sync-type: rsync

    sync-uri: rsync://rsync.gentoo.org/gentoo-portage

    priority: -1000

x-portage

    location: /usr/local/portage

    masters: gentoo

    priority: 0

steam-overlay

    location: /var/lib/layman/steam-overlay

    masters: gentoo

    priority: 50

zugaina

    location: /var/lib/layman/zugaina

    masters: gentoo

    priority: 50

ACCEPT_KEYWORDS="amd64"

ACCEPT_LICENSE="* -@EULA"

CBUILD="x86_64-pc-linux-gnu"

CFLAGS="-march=native -mtune=native -O2 -pipe"

CHOST="x86_64-pc-linux-gnu"

CONFIG_PROTECT="/etc /usr/share/gnupg/qualified.txt"

CONFIG_PROTECT_MASK="/etc/ca-certificates.conf /etc/env.d /etc/gconf /etc/gentoo-release /etc/php/apache2-php7.0/ext-active/ /etc/php/cgi-php7.0/ext-active/ /etc/php/cli-php7.0/ext-active/ /etc/revdep-rebuild /etc/sandbox.d /etc/terminfo"

CXXFLAGS="-march=native -mtune=native -O2 -pipe"

DISTDIR="/usr/portage/distfiles"

FCFLAGS="-O2 -pipe"

FEATURES="assume-digests binpkg-logs config-protect-if-modified distlocks ebuild-locks fixlafiles merge-sync news parallel-fetch preserve-libs protect-owned sandbox sfperms strict unknown-features-warn unmerge-logs unmerge-orphans userfetch userpriv usersandbox usersync xattr"

FFLAGS="-O2 -pipe"

GENTOO_MIRRORS="http://gentoo.osuosl.org/ ftp://gentoo.mirrors.pair.com/ http://gentoo.mirrors.pair.com/ http://mirror.iawnet.sandia.gov/gentoo/ ftp://mirror.iawnet.sandia.gov/pub/gentoo/ http://mirror.usu.edu/mirrors/gentoo/"

LANG="en_US.utf8"

LDFLAGS="-Wl,-O1 -Wl,--as-needed"

MAKEOPTS="-j2"

PKGDIR="/usr/portage/packages"

PORTAGE_CONFIGROOT="/"

PORTAGE_RSYNC_OPTS="--recursive --links --safe-links --perms --times --omit-dir-times --compress --force --whole-file --delete --stats --human-readable --timeout=180 --exclude=/distfiles --exclude=/local --exclude=/packages --exclude=/.git"

PORTAGE_TMPDIR="/var/tmp"

USE="acl alsa amd64 berkdb bzip2 cli cracklib crypt cxx dri ffmpeg flac fpm gdbm gzip hardened iconv ipv6 jpeg justify lame modules mp3 mp4 mpeg multilib ncurses nls nptl openmp pam pax_kernel pcre php pie png readline seccomp session sqlite ssl ssp tcpd tiff unicode urandom x264 xattr xtpax zlib" ABI_X86="64" ALSA_CARDS="ali5451 als4000 atiixp atiixp-modem bt87x ca0106 cmipci emu10k1x ens1370 ens1371 es1938 es1968 fm801 hda-intel intel8x0 intel8x0m maestro3 trident usb-audio via82xx via82xx-modem ymfpci" APACHE2_MODULES="authn_core authz_core socache_shmcb unixd actions alias auth_basic authn_alias authn_anon authn_dbm authn_default authn_file authz_dbm authz_default authz_groupfile authz_host authz_owner authz_user autoindex cache cgi cgid dav dav_fs dav_lock deflate dir disk_cache env expires ext_filter file_cache filter headers include info log_config logio mem_cache mime mime_magic negotiation rewrite setenvif speling status unique_id userdir usertrack vhost_alias" CALLIGRA_FEATURES="kexi words flow plan sheets stage tables krita karbon braindump author" COLLECTD_PLUGINS="df interface irq load memory rrdtool swap syslog" CPU_FLAGS_X86="aes avx avx2 fma3 mmx mmxext popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3" ELIBC="glibc" GPSD_PROTOCOLS="ashtech aivdm earthmate evermore fv18 garmin garmintxt gpsclock isync itrax mtk3301 nmea ntrip navcom oceanserver oldstyle oncore rtcm104v2 rtcm104v3 sirf skytraq superstar2 timing tsip tripmate tnt ublox ubx" GRUB_PLATFORMS="efi-64" INPUT_DEVICES="libinput keyboard mouse" KERNEL="linux" LCD_DEVICES="bayrad cfontz cfontz633 glk hd44780 lb216 lcdm001 mtxorb ncurses text" LIBREOFFICE_EXTENSIONS="presenter-console presenter-minimizer" NGINX_MODULES_HTTP="fastcgi gzip security geo rewrite access lua auth_ldap" OFFICE_IMPLEMENTATION="libreoffice" PHP_TARGETS="php5-6" PYTHON_SINGLE_TARGET="python3_4" PYTHON_TARGETS="python2_7 python3_4" RUBY_TARGETS="ruby21 ruby22" USERLAND="GNU" VIDEO_CARDS="amdgpu fbdev intel nouveau radeon radeonsi vesa dummy v4l" XTABLES_ADDONS="quota2 psd pknock lscan length2 ipv4options ipset ipp2p iface geoip fuzzy condition tee tarpit sysrq steal rawnat logmark ipmark dhcpmac delude chaos account"

Unset:  CC, CPPFLAGS, CTARGET, CXX, EMERGE_DEFAULT_OPTS, INSTALL_MASK, LC_ALL, PORTAGE_BUNZIP2_COMMAND, PORTAGE_COMPRESS, PORTAGE_COMPRESS_FLAGS, PORTAGE_RSYNC_EXTRA_OPTS, USE_PYTHON
```

eix php:

```
Installed versions:  7.0.15(7.0)(08:03:32 AM 05/15/2017)(acl berkdb bzip2 cli crypt ctype curl fileinfo filter fpm gd gdbm hash iconv ipv6 json nls opcache pdo phar posix readline session simplexml sqlite ssl tokenizer unicode xml xmlreader xmlwriter zip zlib -apache2 -bcmath -calendar -cdb -cgi -cjk -coverage -debug -embed -enchant -exif -firebird -flatfile -ftp -gmp -imap -inifile -intl -iodbc -kerberos -ldap -ldap-sasl -libedit -libressl -mhash -mssql -mysql -mysqli -oci8-instant-client -odbc -pcntl -phpdbg -postgres -qdbm -recode -selinux -sharedmem -snmp -soap -sockets -spell -systemd -sysvipc -threads -tidy -truetype -wddx -webp -xmlrpc -xpm -xslt)
```

eix fpm:

```
 Installed versions:  1.10.3^t(12:05:44 PM 05/15/2017)(http http-cache http2 ipv6 pcre pcre-jit ssl -aio -debug -libatomic -libressl -luajit -rtmp -selinux -threads -vim-syntax NGINX_MODULES_HTTP="access auth_ldap fastcgi geo gzip lua rewrite security -addition -auth_basic -auth_pam -auth_request -autoindex -browser -cache_purge -charset -dav -dav_ext -degradation -echo -empty_gif -fancyindex -flv -geoip -gunzip -gzip_static -headers_more -image_filter -limit_conn -limit_req -map -memc -memcached -metrics -mogilefs -mp4 -naxsi -perl -proxy -push_stream -random_index -realip -referer -scgi -secure_link -slice -slowfs_cache -spdy -split_clients -ssi -sticky -stub_status -sub -upload_progress -upstream_check -upstream_ip_hash -userid -uwsgi -xslt" NGINX_MODULES_MAIL="-imap -pop3 -smtp" NGINX_MODULES_STREAM="-access -limit_conn -upstream" USERLAND="GNU")
```

error_log entry: (i put in [WEBSITENAME])

```
2017/05/15 13:03:22 [error] 3732#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.86.1, server: [WEBSITENAME], request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "[WEBSITENAME]"
```

/etc/nginx/nginx.conf

```
user nginx nginx;

worker_processes 2;

error_log /var/log/nginx/error_log info;

events {

        worker_connections 2048;

        use epoll;

}

http {

        include /etc/nginx/mime.types;

        default_type application/octet-stream;

        log_format main

                '$remote_addr - $remote_user [$time_local] '

                '"$request" $status $bytes_sent '

                '"$http_referer" "$http_user_agent" '

                '"$gzip_ratio"';

        client_header_timeout 10m;

        client_body_timeout 10m;

        send_timeout 10m;

        connection_pool_size 256;

        client_header_buffer_size 1k;

        large_client_header_buffers 4 2k;

        request_pool_size 4k;

        output_buffers 1 32k;

        postpone_output 1460;

        gzip off;

        sendfile on;

        tcp_nopush on;

        tcp_nodelay on;

        keepalive_timeout 75 20;

        ignore_invalid_headers on;

        index index.html index.php;

        include /etc/nginx/servers-enabled/*;

        include php.conf;

}

```

/etc/nginx/php.conf (i separated it to make it clean)

```
server {

                listen 127.0.0.1;

                server_name localhost;

                access_log /var/log/nginx/localhost.access_log main;

                error_log /var/log/nginx/localhost.error_log info;

                root /srv/http;

                location ~ .php$ {

                        fastcgi_pass 127.0.0.1:9000;

                        include fastcgi.conf;

                }

        }
```

/etc/nginx/servers-enabled/server.conf

```

server {

    listen 80;

    server_name WEBSITENAME;

    root /srv/http/WEBSITENAME;

    index index.php;

    location / {

      try_files $uri $uri/ /index.php$is_args$args;

    }

    access_log  /var/log/nginx/myBludit.com.access.log;

    error_log   /var/log/nginx/myBludit.com.error.log;

    # Deny direct access to .txt files

    location ~* /bl-content/.*\.txt$ {

        return 404;

    }

    location ~ \.php$ {

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

        fastcgi_pass 127.0.0.1:9000;

        fastcgi_index index.php;

        include fastcgi_params;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_intercept_errors off;

        fastcgi_buffer_size 16k;

        fastcgi_buffers 4 16k;

    }

    location ~ /\.ht {

        deny all;

    }

}
```

ls -l /srv/http

```

drwxr-xr-x  7 nginx nginx 4096 May 15 09:55 WEBSITENAME
```

(the ownership was set with -R)

----------

## Maitreya

Use FPM in an upstream statement instead of a server one.

And while you are at it, use a Unix socket instead of a TCP port as it is limited to localhost anyway.

----------

## iamwill

Thanks, after switching tcp to unix, I am now getting the following error.  The php-fpm.sock shouldn't exist... unless I am missing something, it's supposed to be .socket.  That is what all of the config files have it as.

2017/05/15 14:06:25 [crit] 2629#0: *2 connect() to unix:/run/php-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 192.168.86.1, server: WEBSITENAME, request:  "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php-fpm.sock:", host: "WEBSITENAME"

----------

## saboya

PHP-FPM is probably not configured to create the socket, which sounds about right, I don't think it's the default config. You have to change that yourself.

----------

## iamwill

Thanks saboya and Maitreya,

There were a few issues that you both led me to... the long way around.  First, I didn't have all of the modules that I needed (dom, access, etc..).  Second, some of my configuation files were jacked, went through a rebuilt them to make sure that everything was right (found the hanging .sock and fixed that so that php-fpm worked properly).  

I now have a new issue.  It seems that nothing hosted in any www folder will be writable unless it's 777.  That's no bueno!  It's like nginx isn't the www user, although i've set nginx up that way.  Additionally, it looks like root is writing to all of the files.  If I 777 and make some changes to the website, all of the files that were touched then become owned by root.  Thoughts?

Thanks again for your help guys

----------

## sligo

Usually Nginx would be nginx user. I use to change PHP to run as nginx user as well to have no problems with writing files. Important is, PHP will be the one reading or writing the files. Nginx only routes back and forth between browsers and PHP.

----------

