Kim Ward
Kim Ward

Reputation: 142

Nginx Redirection Loop

I'm very new to NGINX (and bash) and I'm attempting to write a bash script to automate the creation of a new site (so adding a server block) to a webserver. However for some reason my script appears to be putting me into a redirect loop. Any ideas?

cd /var/www/
git clone [email protected]:wardy484/portfolio.git
mv portfolio kimward.co.uk
sudo chmod -R 755 kimward.co.uk

FILE="/etc/nginx/sites-available/kimward.co.uk"

/bin/cat <<EOM >$FILE
server {
    listen 80;
    listen [::]:80;

    root /var/www/kimward.co.uk/public;
    index index.php index.html index.htm;

    server_name kimward.co.uk www.kimward.co.uk;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

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

sudo nano /etc/nginx/sites-available/kimward.co.uk

sudo ln -s /etc/nginx/sites-available/kimward.co.uk /etc/nginx/sites-enabled/
sudo service nginx restart

cd /var/www/kimward.co.uk
composer install
composer update

Upvotes: 0

Views: 114

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47127

$uri, $url, $query_string, etc. are variables and needs to be escaped or they will be expanded by the shell:

location / {
    try_files \$uri \$uri/ /index.php?\$query_string;
}

Same might be the case with other special characters. Instead of having to escape them all you should use << 'EOM' which will treat the here document as a single quoted string.

file="/etc/nginx/sites-available/kimward.co.uk"

/bin/cat <<'EOM' >"$file"
server {
    listen 80;
    listen [::]:80;
    ...
    ...
EOM

I also lower cased $FILE since all uppercase names are reserved for environment variables.

Upvotes: 1

Related Questions