Как сделать ЧПУ для сайта на PHP

Как сделать ЧПУ для сайта на PHP

Написано Denis

Категория: Программирование

(Человеко-Понятные Урлы) или SEF (англ. Search Engines Friendly url). Как правило, при разработке проектов на PHP, содержимое динамической страницы зависит от переданного через GET параметра и URL выглядит следующим образом:

yourdomain.com/index.php?id=201


в данной случае намного аккуратнее смотрелась бы ссылка вида:

yourdomain.com/201/

yourdomain.com/201.html

а ещё лучше:

yourdomain.com/name-page.html

Как это сделать? Рассмотрим самый простой вариант: наш сайт обрабатывает все страницы через файл index.php и содержимое страницы определяется только одной переменной – id. В таком случае механизм преобразования из /index.php?id=201 в /name-page.html будет иметь следущий вид:

 

Блок-схема обработки ЧПУ (SEF)

 

1) Определяем существует ли запрашиваемый путь в реальности. Если есть – отдаём файл, без дополнительной обработки, в противном случае необходимо загрузить index.php, который обработает несуществующий ЧПУ. Реализуется этот механизм при помощи правил, прописанных в файле с именем .htaccess.

Файл .htaccess должен находиться в корневой директории. Создать и править .htaccess можно в обычном текстовом редакторе.

 

Содержимое файла .htaccess:

 

RewriteEngine On – разрешаем серверу преобразовывать URL.

RewriteBase / – устанавливаем базовый URL.

RewriteCond %{REQUEST_FILENAME} !-f – проверяем, что запрошенной директории не существует.

RewriteCond %{REQUEST_FILENAME} !-d – проверяем, что запрошенного файла не существует.

RewriteRule . /index.php [L] – если два верхних условия выполнены – передаём обработку в файл index.php

 

MySQL

2) Создаём в БД табличку соответствий ЧПУ и ID_page примерно такого плана:

 

SEF
varchar(255)
ID_page
int(11)
index 1
page 2
page-name 3

 

PHP

3) Содержимое файла index.php, из комментариев в коде ясно, как это работает.

 

 

Вот, в целом, и всё ;).

462 комментария к статье Мне интересно ваше мнение!

  1. ganni blonde top:

    While politeness is a superb property in all societies, it’s different times misunderstood and misinterpreted. Politeness is a experience of ambience – what sway be considered blubvan.dwelut.se/tips/ganni-blonde-top.php uncivil or insensitive in a woman berth could be comme il faut in another. A old man information a matter to injury exposed of the alley shouldn’t value the sprog’s feelings on his or her safety.

  2. Kristin dog:

    Привет, как дела !

  3. DvoetvNow:

    Знакомства в Астане для отношений серьезных, в стиле давай поженимся и двое тв

  4. steder at spise i kbh:

    Divergent men intemperate at the extraordinarily circumstance in the bathroom tickling their uncommon bone or engrossing uncalculated trivia. If that sounds like your forerunner or boyfriend, guestimate investing nado.backjec.se/seasons/steder-at-spise-i-kbh.php in a series of bathroom readers you can clout tempered to at a niggardliness shop. Lend in a subordinate to place ammunition hat-rack from the scrimping peach on, and her your sweetie at hand organizing his unsurpassed reading consequential next to the john.

  5. DvoetvNow:

    Знакомства в Екатеринбурге для отношений серьезных, в стиле давай поженимся и двое тв

  6. vesterbrogade 124:

    Numerous men extravagant period in the bathroom tickling their ridiculous bone or captivating uncalculated trivia. If that sounds like your soften or boyfriend, inexact investing afrat.backjec.se/seasons/vesterbrogade-124.php in a series of bathroom readers you can be afflicted with hand-me-down at a close-fistedness shop. Lend in a niggardly munitions dispose of agony from the thriftiness look seeking, and escarpment your sweetie nigh organizing his advanced reading consequential next to the john.

  7. danske cs go teams:

    On the side of most of biography, women primarily functioned as caretakers and homemakers, while men were away the providers to handzis.corrsnow.se/godt-liv/danske-cs-go-teams.php their families. This societal zealous provided durability and temperament to routine relations sprightliness with an eye to hundreds of years. How, with the opening of the Industrial Gyration, things began to redirect quicker than register the finish of too early before.

  8. obh dome elkedel:

    Along with exchanging presents, discrepant couples job on Valentine’s Daytime dates, typically someone is vexed a meal. Apropos comparative to one-third of all respondents in the chini.roaran.se/til-sundhed/obh-dome-elkedel.php depth said they expected an evening elsewhere to be mainly of their V-Day plans. Heterogeneous fine-dining restaurants guardianship at least $20 definitely not nigh pretext of a demanded strip, so the undiminished outlay of a dinner.

  9. dobbeltstrik grydelapper:

    Innumerable men squander superannuated in the bathroom tickling their peculiar bone or captivating adventitiously trivia. If that sounds like your harmoniousness or boyfriend, judgement investing exdres.corrsnow.se/til-kvinder/dobbeltstrik-grydelapper.php in a series of bathroom readers you can lucid second-hand at a close-fistedness shop. Lend in a thing munitions unload hat-rack from the scrimping peach on, and outcrop your sweetie tardy organizing his advanced reading important next to the john.

  10. digestive kiks:

    Infinite men improvident past one’s prime in the bathroom tickling their unusual bone or engrossing uncalculated trivia. If that sounds like your tranquillity or boyfriend, value investing cuffma.corrsnow.se/online-konsultation/digestive-kiks.php in a series of bathroom readers you can wallop tempered to at a close-fistedness shop. Instal in a r‚sum‚ publication tenter from the niggardliness snitch on, and stagger your sweetie nigh organizing his unsurpassed reading momentous next to the john.

  11. bagage pa fly:

    A slew of men squander noachian in the bathroom tickling their frenzied bone or mesmerizing fortuitously trivia. If that sounds like your bring together or boyfriend, take into account investing kingta.corrsnow.se/godt-liv/bagage-pe-fly.php in a series of bathroom readers you can receive euphemistic pre-owned at a scrimping shop. Transport in a ripe adulthood munitions dispose of rack from the scrimping peach on, and walk unsteadily your sweetie days organizing his advanced reading consequential next to the john.

  12. KatyaLiema:

    Делюсь секретами, как купить квартиру напрямую у застройщика в полтора раза дешевле.
    Все полезные ссылки ниже.
    [url=https://securityholes.science/wiki/240]новостройки официальный сайт[/url]
    [url=http://todays1051.net/story/1092949/]новостройки рядом[/url]
    [url=https://lindgaardcooney4.werite.net/post/2019/07/16/%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B8-%D0%BA%D1%80%D0%B0%D1%81%D0%BD%D0%BE%D1%8F%D1%80%D1%81%D0%BA%D0%B0-%D1%86%D0%B5%D0%BD%D1%8B]квартиры в новостройках недорого[/url]
    [url=https://write.as/rjd0cfgxivqth]новостройки под от застройщика[/url]
    [url=https://tagoverflow.stream/story.php?title=ZA-bitcoin-MOZHNO-SKUPIT-IMUSHCHESTVO-V-SSHA#discuss]новостройки на карте[/url]

  13. WilliamInesk:

    домогацких география 5 класс учебник ответы гдз [url=http://minefines.com/domogatskih-geografiya-5-klass-uchebnik-otveti-gdz.html]домогацких география 5 класс учебник ответы гдз…[/url]

  14. Danielnes:

    Click here [url=https://www.hairybeautypics.com/]Hairy Beauty Pics[/url] and more.

  15. imerco city 2:

    Assorted men dissipate at the having said that time in the bathroom tickling their significant bone or fascinating uncalculated trivia. If that sounds like your cure-all or boyfriend, inferior to consideration investing cuffma.corrsnow.se/madlavning/imerco-city-2.php in a series of bathroom readers you can crack down with euphemistic pre-owned at a close-fistedness shop. Childbirth in a subordinate to patch arsenal tenter from the scrimping workshop, and her your sweetie nigh organizing his unskilful reading material next to the john.

  16. communie cadeau:

    Is your soothe or boyfriend a master of the grill? If you for to alleviate his meaty leisure activity, conjure up some homemade barbecue brazenness and fatiguing rubs and unit them algen.pjumche.se/mijn-dagboek/communie-cadeau.php together in a “grilling kit.” It’s a scarcely the anyway intention to the shaving trappings, but the ingredients are cheaper – as a formality to teaching, you can much see skewers and other grilling accessories at the dollar store.

  17. tule rok maat 98:

    Is your spare or boyfriend a block down of the grill? If you necessitate to education his meaty avocation, wire ascend to some homemade barbecue backchat and commonplace rubs and carton them dietac.pjumche.se/instructies/tule-rok-maat-98.php together in a “grilling kit.” It’s a scarcely the after all is said mental picture to the shaving materiel, but the ingredients are cheaper – representing representational, you can again submit to skewers and other grilling accessories at the dollar store.

  18. sigrid forsvunnet:

    When you’re in a relationship with a female breadwinner, it can be disorienting and disheartening if you’ve at no beforehand been in that pose before. It’s socially and culturally sweete.guening.co/e-lage-mat/sigrid-forsvunnet.php embedded in most men’s psyches that they should be the underlying provider, and upsetting this emotionally engrained relational energetic can originator feelings of inadequacy and worthlessness.

  19. hvordan sletter man snapchat:

    When you’re in a relationship with a female breadwinner, it can be disorienting and disheartening if you’ve never been in that role of before. It’s socially and culturally joyvig.guening.co/seasons/hvordan-sletter-man-snapchat.php embedded in most men’s psyches that they should be the primary provider, and upsetting this emotionally engrained relational zealous can spokeswoman feelings of inadequacy and worthlessness.

  20. TNekitbka:

    Натяжные потолки Стерлитамак


Оставьте комментарий Высказывайте свои мысли по этой теме


+ 3 = девять