How can I make friendly URLs for my site?

So far I have included everything in index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

There are also pages where I use $ _GET as follows:

SELECT * FROM news WHERE id = ".intval($_GET['id'])

If I want to view the news, enter news?id=1 instead ?page=news&id=1, but I want to be able to use news/1.

Should I add a rewrite rule for every page where I use GET? Or is there a better way?

I hope I do not need to do this for all of my pages.

+3
source share
4 answers

this only rule should allow both with identifiers and without them (and also makes optional slashes):

RewriteRule ^([^/]*)(/([^/]*)/?)?$ index.php?page=$1&id=$3 [QSA,L]

if you do not want to allow / and //, change *to+

+2
source
RewriteRule ^([^/]*)/?([^/]*)$ index.php?page=$1&id=$2 [QSA,L]

www.example.com/page/id

www.example.com/index.php?page=text&id=, .

+5

news/1, . URL- index.php, , .

, "/", , (, "" ), (, "1" ) .

EDIT: URL- PHP.

0

:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ index.php?page=$1 [QSA,L]
RewriteRule ^([^/]+)/(\d+)$ index.php?page=$1&id=$2 [QSA,L]

Or you can parse the requested path using PHP:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php [QSA,L]


// remove the query string from the request URI
$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', $_SERVER['REQUEST_URI']);
// removes leading and trailing slashes and explodes the path
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);
0
source

Source: https://habr.com/ru/post/1702488/


All Articles