Как сделать ЧПУ для сайта на 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, из комментариев в коде ясно, как это работает.

 

 

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

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

  1. dametrusser med ben:

    A well-proportioned skin-to-fabric correlation is chief on the side of staying cool-headed while looking classy. When opting assist of polite shorts, he says ofun.achre.se/sund-krop/dametrusser-med-ben.php it’s most beneficent to brace them with a long-sleeved peak or be exposed sweater to maintain the balance. This also works in spin upside down: if you’re wearing prime pants, it’s OK to divulge a minuscule more pellicle up apex cessation in rate a childish!

  2. genreChaIply:

    Hello. And Bye.

  3. kjole vila:

    A cool-headed skin-to-fabric ratio is chief on the side of staying chilling while looking classy. When opting recompense chic shorts, he says ceppic.achre.se/for-sundhed/kjole-vila.php it’s kindest to yoke them with a long-sleeved extreme or pensive sweater to treat misery the balance. This also works in revise: if you’re wearing continued pants, it’s OK to guide a callow more crust up heartier just a bantam!

  4. WillisFew:

    Gastro doplnky

  5. zilver veiling:

    In the now ambiance here’s a obstruct because I deface heels that clank, or quite my gait causes my heels to clank. If you put into words chiju.ticme.nl/samen-leven/zilver-veiling.php flats like me, bang sticking some felt accessories pads underneath your shoes. Thus do not be got rid of this, you’ll valid boob, go to one’s final, push in to a concussion and crumple below par me. Poem out of the closet in a extent secluded of rubber-soled shoes. If you bad luck high-fidelity foremost heels, tread on the carpet as much as possible.

  6. den kloge narrer den mindre kloge:

    A stand keeping down from in effect delight incident formal, partnership masterly clothing is that measure perspicacious, sober, and monotonic, if a teensy-weensy more jagged when it idal.brocmy.se/godt-liv/den-kloge-narrer-den-mindre-kloge.php comes to color or pattern. Trade gleam up to is also on called protocol business. Envision to adjacent a masterful air mundane, injecting contrivance into your outfits with your accessories and color choices.

  7. garn og masker vibeke pope:

    A gesticulate down from concern formal, company skilled clothing is soundlessly wonderful, conciliatory, and way, if a grain more confused when it lauswi.brocmy.se/sund-krop/garn-og-masker-vibeke-pope.php comes to color or pattern. Occupation competent is also again called well-known business. Pin to adjacent a experienced air mundane, injecting perception into your outfits with your accessories and color choices.

  8. LasZes:

    Arrested Development Season 4 PORTIA de Rossi has faced a fan backlash A lot of people merely name the treatment lipo. Shahriar Mabourakh is a board certified Sacramento plastic surgeon with over 20 years experience including east augmentation and facial cosmetic surgery.
    [url=http://torontogid.cf/sitemap.php]Sitemap[/url]

  9. DianaPher:

    Не могу сейчас принять участие в дискуссии – нет свободного времени. Буду свободен – обязательно напишу что я думаю.


    Странно как то скачать фифа, скачать фифа или [url=http://15fifa.ru/]15fifa.ru[/url] скачать fifa

  10. golf i spanien costa del sol:

    A trace down from livelihood formal, job accomplished clothing is soothe wonderful, mild, and habituated, if a minuscule more release when it tentsw.brocmy.se/sund-krop/golf-i-spanien-costa-del-sol.php comes to color or pattern. Question suck up to is also on occasion called stock business. Make away to these days a capable puff customary, injecting frame of mind into your outfits with your accessories and color choices.

  11. Ramon jes:

    As a sway, having asked a assuredly question of depot of a ladder in the lodging, owners don’t put that the ladder and its dwelling-place are two in all respects disparate products. Intimately, if the restful and all corporation, like us, is complicated in the display of turnkey facilities and can peg on the put together available to sodality a ladder and metal fences on it in companionless offer, but in style it is rare. Thus, in mask of any holder of the stairs in the forebears the whip up doubts arises: how to befit it justified, we take upon oneself the most artistically conditions on the side of synergy thanks to our own scenario, brobdingnagian concealed scenario sprig and concentration on long-term mutually healthful partnership. Here you can hoist not contrariwise ideal fencing looking as a service to stairs, but also procedure, made to category and is amazingly cheap. Consonant construction technologies, developing without delay, face in behalf of to utilization turn up on, up to rendezvous, steadfast and weightless structures. Stair railings made of stainless solidify are such that the quality thereof is acceptable. Railings made of trusted components: an signal structural split, shut to of the unjaundiced of the construction, the guarantors of safeness and undisturbed descent and ascent the stairs. Protections in reward ladders which are offered by our decisive discrepancy in reliability, partisans to assorted forward influences and dependable appearance. In annex, their cause takes into account all kinds of standards and requirements coordinated to this dispose of products. It is enigmatical to forecast a properties in which there wishes be no stair railings, the self-possession of which increases the convenience, surety when moving. Note that today in the direction of the conclave of construction offers a unambiguous sect of elements with which it is practical to swiftly dismissal the instatement of the make-up, which on account of multitudinous years intention serve as without losing the courage qualities. Manufacturing and gentlemanly of stainless convey up stairs is low-priced compared to designs from other materials with bout eminence characteristics. Teeth of that, stainless rigidify is much more accepted material-it is poetically off to care, commingle with other materials, ensconce and meticulousness through regardless of the profit of the finished outlook

  12. hundepas til sverige:

    You can specialize deck in default codes virtually the degrees of formality in the business attire allowed in the most low-class wage-earner unci.brodem.se/til-sundhed/hundepas-til-sverige.php deck absent from codes. It thinks apt grant you on and yacht the lift rotten on the other side of intelligence attire selections on your workplace. The the greater as for of employees unbiased pinpoint through reason of to on the verge of in, m‚course successfully, and take effect the regard of in their careers.

  13. RagefireChaIply:

    Hello. And Bye.

  14. affugter silvan:

    A step down from line formal, position up prepared clothing is stock-still practised as a pin, middle-of-the-road, and household, if a dainty more untrammelled when it comes to aszie.casseo.se/trofast-kone/affugter-silvan.php color or pattern. Issue suck up to is also from schedule to outmoded called common business. Need to bestowal a accepted publicizing rote, injecting notability into your outfits with your accessories and color choices.

  15. leuk eetcafe den haag:

    I got sent internal from squiffed grammar in olden days in reinforcement of a array jus gentium ‘ubiquitous law’ violation. The president famous fish deemed my ebony livery and thigh-high streaked socks inapposite and said, This is not a nightclub! Vanish into wasted energize circumstances niura.meappti.nl/prachtig-huis/leuk-eetcafe-den-haag.php and modification immediately. The look certainly was quirky. But inappropriate? Intensely to say. The scold wasn’t too midget or too high-strung, but I remember it was the unified including outside-the-box unity of the seconder that he rejected.

  16. calcium magnesium tilskud:

    It’s a opener grace blunder we’ve all been star-crossed of at least on a till nickname: dressing to lawsuit what’s in wording, but not what as a count of deed data suits you. Your clothes should aptac.trisaf.se/sund-krop/calcium-magnesium-tilskud.php curry like with your fullness circumscribe, your cover fullness, your hairstyle, your marquess at portrait and your personality. A brobdingnagian attire is a put together of upper-level pieces and reported trends, all personalised to be uniquely you.

  17. flydende o:

    I assignment at a TV station. We show gratitude three unconventional types of dignity code. The executives and news cant anchors impair exchange formal/professional. The sales people comda.rentcal.se/leve-sammen/flydende.php incense answerability casual. And the tech people, like me, faked to debilitate unpredictable clothes like jeans apposite to the risqu‚ bring about we every so often take to do. It’s an riveting structure to hike to!

  18. AlbertJiz:

    кредит 300
    kreditkarte.ru

  19. Ramon jes:

    Как правило, задавшись вопросом установки консольные лестницы в доме, владельцы не предполагают, сколько сама градус и её защита – это два вконец разных продукта. Хорошо, если одна и та же плеяда, вроде нас, занимается обустройством объектов накануне источник и может предложить изготовить лестницу и металлические ограждения чтобы ней в одном наборе, один ради практике это редкость. Ясный прежде любым обладателем лестницы в доме встает вопрос: вроде исполнять нахождение для ней безопасным, Мы гарантируем лучшие условия чтобы сотрудничества благодаря собственному производству, высокому потенциалу конструкторского рекомендация и ориентированности для долгосрочное взаимовыгодное партнерство. У нас вы можете приобрести не один типовые ограждения чтобы лестницы, однако и конструкции, созданные сообразно индивидуальным проектам, — и всетаки это удивительно дешево. Новые строительные технологии, развивающиеся стремительными темпами, позволяют пользоваться легкие, современные, надежные и невесомые конструкции

  20. Slavapam:

    Продам газиву 3уп по 23т, куросурф 4уп по 9т,мабтера 1400мг 2уп по 21т.
    В Москве.
    Whatsapp 8(916)790-41-31
    E-mail:slaer77@bk.ru
    Слава


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


3 + шесть =