Nginx rewrite or internal redirection cycle while internally redirecting to index html

rewrite or internal redirection cycle while internally redirecting to, in nginx

There are two common ways of using Nginx with PHP projects:

Nginx serves static files, PHP processing is done by PHP-FPM daemon and proxied by Nginx using FastCGI

This is a common scenario to setup a dedicated server to get best performance and you should use it unless your application heavily relies on some Apache’s features like .htaccess and you cannot write this once and for all inside Nginx config.

server < . root /home/test/web/foo.co.uk/public_html; fastcgi_index index.php; location / < try_files $uri $uri/ /index.php?$args; >location ~ \.php$ < include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; >location ~* ^.+\.(jpg|jpeg|gif|png|ico|svg|css|zip|tgz|gz|rar|bz2|exe|pdf|doc|xls|ppt|txt|odt|ods|odp|odf|tar|bmp|rtf|js|mp3|avi|mpeg|flv|html|htm)$ < access_log /var/log/apache2/domains/foo.co.uk.log combined; access_log /var/log/apache2/domains/foo.co.uk.bytes bytes; expires max; >> 

Nginx serves static files, everything else is proxied to an internal Apache daemon

In this case PHP processing is done by Apaches mod_php module. The setup is something like this:

server < . root /home/test/web/foo.co.uk/public_html; location / < proxy_pass https://178.79.134.35:8443; >location ~* ^.+\.(jpg|jpeg|gif|png|ico|svg|css|zip|tgz|gz|rar|bz2|exe|pdf|doc|xls|ppt|txt|odt|ods|odp|odf|tar|bmp|rtf|js|mp3|avi|mpeg|flv|html|htm)$ < access_log /var/log/apache2/domains/foo.co.uk.log combined; access_log /var/log/apache2/domains/foo.co.uk.bytes bytes; expires max; >> 

There is no need in fallback code for static files unless you want your apache to generate a heavy 404 page. This also can be set up in nginx with error_page directive.

Also, in this case please consider connecting to Apache on a loopback interface on a plain HTTP port fo better performance. HTTPS should be set up on the front-end web server only. Proxying to a HTTPS-enabled port on the same host does not really give you any benefit.

UPDATE: I used TCP socket connection to PHP-FPM in my examples just for the sake of example. However there are many benchmarks on the Internet that showed better performance for local UNIX sockets rather than TCP sockets. For Nginx it’s fairly easy to use UNIX socket as well:

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

Make sure to check access permissions to that file and corresponding path.

Nginx

DevOps & SysAdmins: rewrite or internal redirection cycle while internally redirecting to, in nginx

Nginx Tutorials #5 - Redirect Url (Index, Error_page, Return, Rewrite and Try_files)

NGINX Rewrite and Redirect

DevOps & SysAdmins: nginx yet another rewrite or internal redirection cycle

Andrew Newby

Andrew Newby

Updated on September 18, 2022

Comments

Andrew Newby

I’m trying to get a rewrite rule to work for nginx and WordPress. After a reboot of nginx, I try the site and get an IS 500 error page. The log file says:

*1 rewrite or internal redirection cycle while internally redirecting to "/index.php" 

I’m confused, as this is how they tell you to do it in all the tutorials (and even the WordPress documentation for setting up rewrite rules with nginx):

 try_files $uri $uri/ /index.php?$args ; 
server < listen 178.79.134.35:443 http2; listen [::]:443 http2; server_name foo.co.uk www.foo.co.uk cdn.foo.co.uk; ssl on; ssl_certificate /home/test/conf/web/ssl.foo.co.uk.pem; ssl_certificate_key /home/test/conf/web/ssl.foo.co.uk.key; error_log /var/log/apache2/domains/foo.co.uk.error.log error; location / < # This is cool because no php is touched for static content. # include the "?$args" part so non-default permalinks doesn't break when using query string try_files $uri $uri/ /index.php?$args ; proxy_pass https://178.79.134.35:8443; location ~* ^.+\.(jpg|jpeg|gif|png|ico|svg|css|zip|tgz|gz|rar|bz2|exe|pdf|doc|xls|ppt|txt|odt|ods|odp|odf|tar|bmp|rtf|js|mp3|avi|mpeg|flv|html|htm)$ < root /home/test/web/foo.co.uk/public_html; access_log /var/log/apache2/domains/foo.co.uk.log combined; access_log /var/log/apache2/domains/foo.co.uk.bytes bytes; expires max; try_files $uri @fallback; >> location /error/ < alias /home/test/web/foo.co.uk/document_errors/; >location @fallback < proxy_pass https://178.79.134.35:8443; >location ~ /\.ht location ~ /\.svn/ location ~ /\.git/ location ~ /\.hg/ location ~ /\.bzr/ include /home/test/conf/web/snginx.foo.co.uk.conf*; > 

UPDATE 2: As suggested, I know how a location ~ \.php$ < >block wrapped around it. So it looks like:

location / < proxy_pass https://178.79.134.35:8443; location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME home/test/web/foo.co.uk/public_shtml$fastcgi_script_name; include fastcgi_params; >location ~* ^.+\.(jpg|jpeg|gif|png|ico|svg|css|zip|tgz|gz|rar|bz2|exe|pdf|doc|xls|ppt|txt|odt|ods|odp|odf|tar|bmp|rtf|js|mp3|avi|mpeg|flv|html|htm)$ < root /home/test/web/foo.co.uk/public_shtml; access_log /var/log/apache2/domains/foo.co.uk.log combined; access_log /var/log/apache2/domains/foo.co.uk.bytes bytes; expires max; try_files $uri @fallback; >try_files $uri $uri/ /index.php?$args ; > 

111: Connection refused) while connecting to upstream, client: 81.174.134.133, server: foo.co.uk, request: «GET /wp-admin/ HTTP/2.0», upstream: «fastcgi://127.0.0.1:9000»

[email protected]:/home/# telnet localhost 9000 Trying ::1. Trying 127.0.0.1. telnet: Unable to connect to remote host: Connection refused 

So it doesn’t seem to be able to access it. I’m a bit confused though, as the firewall is setup to allow port 9000:

ACCEPT tcp -- anywhere anywhere tcp dpt:9000 

UPDATE 2: As suggested, I tried: netstat -nltp|grep 9000 . but it gives no result. If I look though, I can see php-7.0-fpm installed and running (as far as I can tell);

[email protected]:~# service php7.0-fpm status â php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2017-04-12 12:06:48 UTC; 18h ago Process: 3560 ExecStartPre=/usr/lib/php/php7.0-fpm-checkconf (code=exited, status=0/SUCCESS) Main PID: 3800 (php-fpm7.0) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" CGroup: /system.slice/php7.0-fpm.service ââ3800 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf) ââ3872 php-fpm: pool www ââ3882 php-fpm: pool www Apr 12 12:06:43 com.x.com systemd[1]: Starting The PHP 7.0 FastCGI Process Manager. Apr 12 12:06:48 com.x.com systemd[1]: Started The PHP 7.0 FastCGI Process Manager. 

I looked in /etc/php/7.0/fpm/php-fpm.conf , but don’t see any reference to a «listen» port UPDATE 3: I found a post where they said about editing the www.conf file: https://github.com/serghey-rodin/vesta/issues/1025 So looking for that on my server, I found: /etc/php/7.0/fpm/pool.d/www.conf I then commented out:

listen = /run/php/php7.0-fpm.sock 

. and then rebooted with: service php7.0-fpm restart And now I can see it on the netstat I then made sure I had this in my config:

Читайте также:  Html loader что это

Источник

php + nginx = 500 error, help fix please

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya, Your issue seems to be related to a redirection loop in your NGINX configuration. Let’s try to address it. You have this block in your server configuration:

location /  try_files $uri $uri/ /index.html; > 

What it does is it tries to serve the request URI as a file if it exists ( $uri ), then as a directory if it exists ( $uri/ ), and then falls back to /index.html if neither exists. If /index.html does not exist, NGINX will keep trying to redirect to /index.html because of the try_files directive, leading to the redirection loop. The solution to this issue depends on your application. If you are running a PHP application, you probably want to redirect to /index.php instead of /index.html :

location /  try_files $uri $uri/ /index.php; > 

If you are serving a static website and /index.html should exist but doesn’t, you need to check that the file is present in the /var/www/project/public directory and that NGINX has sufficient permissions to read the file. Remember to restart or reload the NGINX server after making changes to the configuration:

sudo systemctl restart nginx 

Kindly check if this file is available or not. /var/run/php5-fpm.sock And restart the php-fpm server

No idea what are you trying, but did you just made a rewrite to fix the loop?

Also whats the point of this with an html file?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NGINX error: rewrite or internal redirection cycle while internally redirecting to «/index.php» #11

NGINX error: rewrite or internal redirection cycle while internally redirecting to «/index.php» #11

Comments

This is happening for the first time and never had this before, but on a forge server I’m getting the following error:

rewrite or internal redirection cycle while internally redirecting to "/index.php" 

And the Nginx Config as used in your forge-example.

# FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/dedansacademie.be/before/*; # Bots to ban via user agent map $http_user_agent $limit_bots < default 0; ~*(AhrefsBot|Baiduspider|PaperLiBot) 1; >server < # Listen for both IPv4 & IPv6 requests on port 443 with http2 enabled listen 443 ssl http2; listen [::]:443 ssl http2; # General virtual host settings server_name dedansacademie.be; root /home/forge/dedansacademie.be/current/public; index index.html index.htm index.php; charset utf-8; # Ban certain bots from crawling the site if ($limit_bots = 1) < return 403; ># 404 error handler error_page 404 /index.php?$query_string; # 301 Redirect URLs with trailing /'s as per https://webmasters.googleblog.com/2010/04/to-slash-or-not-to-slash.html rewrite ^/(.*)/$ /$1 permanent; # Change // -> / for all URLs, so it works for our php location block, too merge_slashes off; rewrite (.*)//+(.*) $1/$2 permanent; # Handle Do Not Track as per https://www.eff.org/dnt-policy location /.well-known/dnt-policy.txt < try_files /dnt-policy.txt /index.php?p=/dnt-policy.txt; ># For WordPress bots/users location ~ ^/(wp-login|wp-admin|wp-config|wp-content|wp-includes|(.*)\.exe) < return 301 https://wordpress.com/wp-login.php; ># Access and error logging access_log off; error_log /var/log/nginx/dedansacademie.be-error.log error; # If you want error logging to go to SYSLOG (for services like Papertrailapp.com), uncomment the following: #error_log syslog:server=unix:/dev/log,facility=local7,tag=nginx,severity=error; # FORGE SSL (DO NOT REMOVE!) # ssl_certificate; # ssl_certificate_key; ssl_certificate /etc/nginx/ssl/dedansacademie.be/292771/server.crt; ssl_certificate_key /etc/nginx/ssl/dedansacademie.be/292771/server.key; # SSL/TLS configuration, with TLSv1.0 disabled because it is insecure; note that IE 8, 9 & 10 support # TLSv1.1, but it's not enabled by default clients using those browsers will not be able to connect ssl_protocols TLSv1.2 TLSv1.1; ssl_prefer_server_ciphers on; ssl_dhparam /etc/nginx/dhparams.pem; ssl_ciphers 'ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5'; ssl_buffer_size 4k; ssl_session_timeout 4h; ssl_session_cache shared:SSL:40m; ssl_stapling on; ssl_stapling_verify on; #ssl_trusted_certificate /etc/nginx/ssl/lets-encrypt-x3-cross-signed.pem; # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/dedansacademie.be/server/*; # Load configuration files from nginx-partials include /etc/nginx/nginx-partials/*.conf; # Root directory location handler location / < try_files $uri/index.html $uri $uri/ /index.php?$query_string; ># Localized sites, hat tip to Johannes -- https://gist.github.com/johanneslamers/f6d2bc0d7435dca130fc # If you are creating a localized site as per: https://craftcms.com/docs/localization-guide # the directives here will help you handle the locale redirection so that requests will # be routed through the appropriate index.php wherein you set the `CRAFT_LOCALE` # Enable this by un-commenting it, and changing the language codes as appropriate # Add a new location @XXrewrites and location /XX/ block for each language that # you need to support #location @enrewrites < # rewrite ^/en/(.*)$ /en/index.php?p=$1? last; #># #location /en/ < # try_files $uri $uri/ @enrewrites; #># Craft-specific location handlers to ensure AdminCP requests route through index.php # If you change your `cpTrigger`, change it here as well location ^~ /admin < try_files $uri $uri/ /index.php?$query_string; >location ^~ /cpresources < try_files $uri $uri/ /index.php?$query_string; ># php-fpm configuration location ~ [^/]\.php(/|$) < try_files $uri $uri/ /index.php?$query_string; fastcgi_split_path_info ^(.+\.php)(/.+)$; # Change this to whatever version of php you are using fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param HTTP_PROXY ""; fastcgi_intercept_errors off; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; >location ~ /\.ht < deny all; >> # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/dedansacademie.be/after/*; 

Maybe you should look into this? Since this is a really weird issue .

The text was updated successfully, but these errors were encountered:

Источник

Что означает эта ошибка nginx «цикл перезаписи или внутреннего перенаправления»?

Я получаю их из журнала ошибок nginx, у меня нет поддомена «kowol», у меня нет ссылок на qq.com или joesfitness.net на моем сайте. В чем дело?

Редактировать: Конфигурация Nginx по умолчанию:

server < listen 8080; ## listen for ipv4; this line is default and implied listen [::]:8080 default ipv6only=on; ## listen for ipv6 root /usr/share/nginx/www; index index.php index.html index.htm; # Make site accessible from http://localhost/ server_name _; location / < # First attempt to serve request as file, then # as directory, then fall back to index.html try_files $uri $uri/ /index.html; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules >location /doc/ < alias /usr/share/doc/; autoindex on; allow 127.0.0.1; deny all; ># Only for nginx-naxsi : process denied requests #location /RequestDenied < # For example, return an error code #return 418; #>#error_page 404 /404.html; # redirect server error pages to the static page /50x.html # #error_page 500 502 503 504 /50x.html; #location = /50x.html < # root /usr/share/nginx/www; #># pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # 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; ># deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht < # deny all; #>> 

Все странно, хотя я готов поспорить, что проблема в следующем:

 try_files $uri $uri/ /index.html; 

Проблема здесь в том, что второй параметр, здесь, $uri/ заставляет каждый из файлов в вашей index директиве быть проверенным по очереди. Если ничего не найдено, он затем переходит к /index.html , что приводит location к повторному вводу того же блока, и, так как он все еще не существует, вы получаете бесконечный цикл.

вернуть ошибку 404, если ни один из индексных файлов, указанных вами в index директиве, не существует.

Кстати, те запросы, которые вы видите, являются фоновым шумом в Интернете . В частности, они представляют собой тесты, позволяющие определить, является ли ваш веб-сервер открытым прокси-сервером, и его можно использовать для сокрытия происхождения злонамеренного пользователя, когда он отправляется на вредоносную деятельность. Ваш сервер не является открытым прокси в этой конфигурации, поэтому вам не нужно беспокоиться об этом.

Источник

Оцените статью