Nginx убрать index php

Remove index.php from Joomla! URLs with NGINX

How do I remove index.php from my Joomla URLs? For example: http://domain.com/index.php/webpage should become http://domain.com/webpage I’ve been following some guides that I’ve found but it all result in a redirect loop, 404 or internal server error. I need some guidance please. Here is my current config (excluding failing attempts).

server < listen [::]:80; server_name www.domain.com; return 301 http://domain.com$request_uri; >server < listen [::]:80; server_name domain.com; root /usr/share/nginx/www; index index.php index.html index.htm; location / < try_files $uri $uri/ /index.php?$args; >location ~/favicon.ico < access_log off; log_not_found off; >location ~ \.php$ < try_files $uri /index.php; include fastcgi_params; fastcgi_pass unix:/var/run/php5-fpm.sock; >access_log /var/log/nginx/$host-access.log; error_log /var/log/wpms-error.log; > 

1 Answer 1

How do I remove index.php from my Joomla URLs? For example: http://example.com/index.php/webpage should become http://example.com/webpage . I’ve been following some guides that I’ve found, but it all result in a redirect loop…

As explained at nginx redirect loop, remove index.php from url, you’d want something like this to make sure there aren’t any redirect loops:

index index.php index.html index.htm; if ($request_uri ~ "^/(.*)(? 

The above assumes that manually omitting the index.php part of the URL is already handled correctly through the rest of your configuration.

Источник

Убираем .html, .php и .htm в конце URL-адресов на Apache/Nginx

Часто слышу, что сеошники советуют убирать окончания .html, .php и .htm в адресах ваших сайтов – якобы, это негативно влияет на продвижение. Кто-то же говорит, что это просто визуально добавляет адресу лишний мусор.

В любом случае, убирать или оставлять эти окончания, решать вам, я же покажу, как это реализовать на статичном сайте (то есть сайте, находящемся не на CMS). Почему только на статичном? Потому что для различных CMS это реализовывается разными методами, о которых я также расскажу в последующих статьях.

Не утверждаю на 100%, что этот метод не будет работать на какой-то из CMS – пробуйте и о результатах отписывайтесь в комментариях.

Убираем .html, .php и .htm на Apache

Как вы знаете, в Apache существует файл .htaccess, который содержит в себе набор настроек и конфигураций сервера. С его помощью мы и будем убирать ненужные нам окончания.

1. Подключитесь к сайту по FTP и в корне сайта найдите файл .htaccess. Откройте его. Если такой файл отсутствует – создайте.

2. Найдите строчку, содержащую:

Читайте также:  Apache soap java client

Сразу после нее вставьте следующие правила.

Если вам необходимо убрать .php:

 RewriteCond %{REQUEST_FILENAME> !-f RewriteRule ^([^.]+)$ $1.php [NC,L]

Если вам необходимо убрать .html:

 RewriteCond %{REQUEST_FILENAME> !-f RewriteRule ^([^.]+)$ $1.html [NC,L]

Если вам необходимо убрать .htm:

 RewriteCond %{REQUEST_FILENAME> !-f RewriteRule ^([^.]+)$ $1.htm [NC,L]

Если строчка «RewriteEngine On» отсутствует в файле – добавьте ее в самое начало.

После чего сохраните изменения и отправьте файл обратно на сайт. Если раньше адреса на вашем сайте были вида

 https://www.pandoge.com/page.php

то теперь вы можете открыть эту страницу по адресу:

Убираем .html, .php и .htm на Nginx

1. Для того чтобы подобную настройку произвести в Nginx, откройте файл конфигурации по адресу:

в FTP (если вам позволяют права) либо через панель управления сервером.

2. Далее, в секцию location / , вставляем необходимые правила.

Если вам необходимо убрать .php:

Если вам необходимо убрать .html:

Если вам необходимо убрать .htm:

Если в процессе настройки у вас что-то не получается – пишите об этом в комментариях.

Установка бесплатного сертификата от Let’s Encrypt на сайт с сервером CentOS 6 + ISPmanager 4 + Nginx + Apache

Источник

Removing index files from the URL with Nginx

At work we are switching from a shared LAMP stack to a VPS running nginx. I’m significantly more comfortable with Apache but learning to use Nginx has been pretty exciting (or as exciting as learning to configure a new webserver can be. The current issue is this: on several domains we need to remove index.php from the URL for canonicalization. This is the last thing that we currently need to take care of for these domains. I’ve been researching plenty of different techniques for removing index.php from a URL (most of which are specifically for CI or ExpressionEngine) and I’ve tried to adapt several of these for personal use but I end up with an infinite loop error which I can only imagine is related to the following:

I’m hell-bent on learning how all of this works but right now I need to ask for help figuring this out so that we can move forward and I can figure out what it is that I’m doing wrong. I would greatly appreciate any responses and will further appreciate anyone who is willing to go a little in-depth on the subject to help someone new like myself and anyone else who might be in a similar situation that reads this. Thank you! UPDATE
To make things easier I’m just going to put my nginx config up here for this vhost.

server < listen 80; server_name examplesite.com; # redirect non-www to www. for canonical urls rewrite ^/(.*) http://www.examplesite.com/$1 permanent; >server < listen 80; server_name www.examplesite.com; error_log /srv/http/nginx/examplesite.com/log/nginx-error.log; access_log /srv/http/nginx/examplesite.com/log/nginx-access.log; root /srv/http/nginx/examplesite.com/root; location / < try_files $uri $uri/ /index.php?$args =404; >location ~ \.php$ < include fastcgi.conf; fastcgi_param PHP_ADMIN_VALUE "error_log=/srv/http/nginx/examplesite.com/log/php-error.log"; fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; >

Источник

Читайте также:  Как проверить начало строки java

How to remove both .php and .html extensions from url using NGINX?

With some research I’ve made the first case to work. It`s done by following configuration:

It works for indexhtml.html displaying as indexhtml, but nothing happens with .php. If I change $uri.html to $uri.php, it works neither for .html, neither .php. I`ve tried to put something similar in php location but without any success.

No, I do not need extension at all. That s only for example to understand, that I m not an weirdo, who s having both index.php and index.html files on my server. However, it s already solved.

5 Answers 5

From what I’ve researched, if you append your /etc/nginx/conf.d/domain.tld.conf file to include:

location / < try_files $uri $uri.html $uri/ @extensionless-php; index index.html index.htm index.php; >location ~ \.php$ < try_files $uri =404; >location @extensionless-php

Then restart nginx and give it a go. Hopefully this will help you! More information can be found (where I found it) here @ tweaktalk.net

Funny. If I delete code try_files $uri.html $uri/ =404; code from my previous configuration and add Yours, than everything works fine with php, but doesn`t work with html. If I do not remove previous line and add Yours, «Problem loading page» shows up. How can I combine them to work both?

Try changing your ‘try_files’ line under ‘location’ to: try_files $uri $uri.html $uri/ @extensionless-php; Or possibly: try_files $uri $uri.html $uri/ @extensionless-php $uri/ =404;

Thanks a lot! I replaced try_files $uri $uri/ @extensionless-php; with try_files $uri.html $uri/ @extensionless-php; and it`s finally working both for html and php. Great!

Incase you have installed nginx on Windows n cant seem to find «/etc/nginx/conf.d/domain.tld», then this is actually the same as «nginx/conf/nginx.conf»

No need for extra blocks and named locations and everything. Also move the index line outside the location block

Keep in mind that if you have a folder and a file with the same name inside the same folder, like /folder/xyz/ and /folder/xyz.php you won’t be able to run the php file if the folder xyz contains an index.php or index.html , just keep this in mind.

@elbowlobstercowstand, just another addition, when using $query_string , I prefer using $is_args instead of a plain ? would be a tiny bit cleaner when there’s no actual args by not having a trailing ? in the url.

Just to add, the important bit in making this work is the =404 needs to be in the try_files in the .php block, not at the end of the location / one, otherwise you’ll get 404 errors for URLs for which a .php file does exists.

@elbowlobstercowstand was right, I rolled back his last edit, nginx will not see the _GET array if ?$query_string was not added.

Читайте также:  Css hide text content

To further Mohammad’s answer, you might also want to offer redirects from .html and .php to the extensionless versions.

This can be accomplished due to the fact that $request_uri contains «full original request URI (with arguments)», and is not affected by the internal rewrites that are not visible to the user.

server < index index.html index.php; location / < if ($request_uri ~ ^/(.*)\.html$) < return 302 /$1; >try_files $uri $uri/ $uri.html $uri.php?$args; > location ~ \.php$ < if ($request_uri ~ ^/([^?]*)\.php($|\?)) < return 302 /$1?$args; >try_files $uri =404; # add fastcgi_pass line here, depending if you use socket or port > > 

Источник

Remove .php extension with NGiNX

Removing .php or .html extension from your website URL when using NGiNX can be quite frustrating, luckily there is a quick and simple solution that we can use in order to fix this and no, it is not called .htaccess as you used to do it when using Apache as web server. It is a nice and elegant solution where you can manage this straight from your .conf file. In this short tutorial we will guide you step by step how to remove .php and .html extension from your URL when using NGiNX, this is a pretty good solution to boost your SEO and get some really nice and friendly website URLs.

Table of contents

Edit the .conf file

On our first step we’ll have to open and edit the appropriate configuration file. If you have no custom .conf file then you will typically the default file can be found at /etc/nginx/nginx.conf , please open it as shown in the example below using vi or whatever editor you like:

Remove .php and .html extensions from URL

On this step we have to add the following code lines inside the server block in order to remove the .php and .html extensions from your URLs, please use the below example:

 server < . location / < try_files $uri $uri.html $uri/ @extensionless-php; index index.html index.htm index.php; >location ~ \.php$ < try_files $uri =404; >location @extensionless-php < rewrite ^(.*)$ $1.php last; >. > 

Make sure you save the changes and lets move on to our next step.

Reload NGINX web server

Finally in order for our changes take effect we have to reload NGINX server, depending on your Linux distro you may have to use service [service_name] reload or systemctl reload [service_name] , we will use systemctl on this particular example:

That’s it, now simply open a browser and go to a URL without its .php or .html extension. For example, go to /index instead of /index.php and your browser should load the page, if that doesn’t work simply restart NGiNX, that should work.

Источник

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