I have developed a website with PHP, MySQL, CSS, Javascript and HTML. The problem that I find is that when you make the pages dynamic, the URLs are usually like this:
/tests.php?ID=2
/panel.php?ID=7&GENERO=2
/specifies.php?ID=326&GENERO=2&CATEGORY=7
And of course, all this does not like google very much.
I wanted to know if it is possible to remove the extensions .php
and create friendly urls.
I use an NGINX server .
My .conf file that loads the web:
server {
listen 8360;
listen [::]:8360;
root /var/www/laboratorio/;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html index.php;
server_name 82.223.13.57;
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { expires 365d; } location ~* \.(css|js|pdf)$ { expires 30d; }
location ~ ^/.well-known {
allow all;
}
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
error_page 405 = $uri;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
location ~ /\.ht {
deny all;
}
}
There are many frameworks that use "friendly URLs" and on their websites they show the typical configuration for this type of scenario.
To begin with, you should create a single input PHP file that we will call "router". It will be the script in charge of collecting all the HTTP requests and calling the appropriate PHP based on the parameters given to it.
In Slim, for example, the instructions for "rewriting" the URLs are here :
The "magic" is created on this line:
It first tries, if it exists, to load the CSS, JS or image file from the file system. If it does not exist, it passes the request to the router (
index.php
).Also, you can create a unique file rule for PHP as suggested in the configuration file (instead of file pattern ending in
.php
):Your router will receive the request with the URL in
$_SERVER['REQUEST_URI']
. You need to parse that variable for which PHP to run and what parameters to pass to it.Edition:
With the additional data provided in the question I can suggest the following modifications:
Capturing requests
You have two options to get it.
Using
try_files
:Using
error_page
:request router
To maximize compatibility with your existing application you should create a script as an entry point to the rest of your PHP scripts, modifying the parameters
GET
according to the content of the URL.File example
enrutador.php
:Examples of supported URLs
Here are examples of your URLs compared to those supported by the router:
As you can see, the descriptions can be arbitrary and they are the ones that will help the search engine to understand the content of your URLs.