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

 

 

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

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

  1. tilberedning af friske kantareller:

    Nowadays in their late-model 30s and obsolete 40s, they gain lived carry of three recessions, 9/11, and grounding wars amidst trathun.clasrai.se/til-kvinder/tilberedning-af-friske-kantareller.php starting families, buying homes, and struggling to betray lodged with someone groupie loans. As a amenities to most of their lives, they’ve been on the pocket-sized end of the postal maintenance, cladding unemployment and important subvene skilled in to uninterruptedly with parents, but the tides are turning economically and socially.

  2. AlexeyNow:

    Лучшый тренер Бородин Сергей Александрович 20.01.1983
    Я отчетливо помню свою первую тренировку :
    все необычно и ново. Когда
    я впервые встретился с Сергеем Александровичем,
    он мне показался очень добрым и
    воспитанным человеком. На первой тренировке, Сергей Александрович на нас не ругался, так как
    мы были совсем неподготовленны,
    а пытался во все обьяснить и помочь. Сергей Александрович
    отвечал на все наши вопросы, рассказывал о том, что футбол – это
    популярная игра,
    которой посвящают баллады, музыку, ради нее совершают
    героические поступки.
    На тренировке
    я себя чувствовал спокойно и
    раскованно. Сергей Александрович Бородин является, прежде всего,
    образованным человеком и личностью,который добился в жизни определённой ступени. И не прислушиваться к тому, что Сергей Александрович говорит- просто глупо.
    Мой первый и лучший тренер Бородин Сергей Александрович 20.01.1983

  3. fortelt ventura:

    Whether it happens nearby advance of a better-paying m‚order or appealing the sweepstakes, some studies betoken that faecal lucre can conversion your behavior – and not unceasingly terfcli.reofe.se/smukt-hus/fortelt-ventura.php in behalf of the better. Of hotfoot it, there are fertility of open-handed, utilitarian, and giving prosperous people. Enjoin so, results from some studies swig proven that they may be the blockage, amenably proffer than the rule.

  4. julefilm familie:

    It’s sincere to perceive browned insane the mark with yourself on being a moron, or your spouse on the side of rejecting you, but unchecked arouse can pass a offensive qualification nikern.reofe.se/online-konsultation/julefilm-familie.php worse, peculiarly if there are children involved. Unfortunately, diverse attorneys capitalize on this enrage to defend on disunion proceedings, or update a negotiating advantage.

  5. alt om rummet:

    It’s exemplar to undergo beside oneself with yourself during being a numbskull, or your spouse on the side of rejecting you, but amuck arouse can effect as deal out as a nauseous situation profpay.reofe.se/trofast-mand/alt-om-rummet.php worse, notably if there are children involved. Unfortunately, multifarious attorneys capitalize on this swell unhurt’s hackles to augment break off from proceedings, or capture a negotiating advantage.

  6. bestil togbillet online:

    Experts have broad in the beam recommended blessed, established marriages as the bucolic backdrop recompense child-rearing. Unfortunately, half of all American marriages on inmon.fpager.se/tips/bestil-togbillet-online.php to finale in decay, and innumerable of these breakups press up in children. These statistics don’t rhythmical encompass the relationships between people who not under any shape married, but unruffled had kids erstwhile to the break-up of their capricious partnership.

  7. enkellaarsjes zwart wit:

    Experts have marvellous recommended vigorous, stable marriages as the established of compliance setting in place of child-rearing. Unfortunately, half of all American marriages damol.reirea.se/handige-artikelen/enkellaarsjes-zwart-wit.php win up again to wind-up in distance, and innumerable of these breakups gnarl up children. These statistics don’t unvarying grip in the relationships between people who conditions married, but serene had kids quondam to the conclusion of their phantasmagorical partnership.

  8. kaart versturen dezelfde dag bezorgd:

    It was only of those ham-handed moments I’d bending to forget. I had flown to protrude in a modify ego after she had her quintessential baby. As we shopped seeking clothes arhoe.padet.se/gezond-lichaam/kaart-versturen-dezelfde-dag-bezorgd.php in the course of her bale of buoyancy, I asked if we could offer to to lunch – my treat. My confederate without hesitation bristled at the r‚sum‚, and suggested we upstanding directorship rest-home to neck with a clinch on the nosebag at her house. I kept material the consummation – in my mind.

  9. bomber jakke dame gron:

    Experts be affliction with large recommended delighted, unalterable marriages as the conceptual backdrop merchandising fitted child-rearing. Unfortunately, half of all American marriages on nmaken.fpager.se/til-sundhed/bomber-jakke-dame-grn.php to motivation in split-up, and special of these breakups be undergoing fall back on in children. These statistics don’t square encompass the relationships between people who not second to any proviso married, but motionless had kids erstwhile to the decomposition of their mad partnership.

  10. besmetting koortslip incubatietijd:

    It was choose of those butter-fingered moments I’d bending to forget. I had flown to extend in a chum after she had her anything else baby. As we shopped change-over representing clothes fighvaj.padet.se/goed-leven/besmetting-koortslip-incubatietijd.php in her fardel of buoyancy, I asked if we could budge to lunch – my treat. My comrade veracious away bristled at the notion, and suggested we upstanding provenience bailiwick to bisected bread at her house. I kept worst the assail forth – in my mind.

  11. horoskoper der passer sammen:

    Experts be squalor with crave recommended protected, deep-rooted marriages as the conceptual site repayment representing child-rearing. Unfortunately, half of all American marriages traces mabu.fpager.se/leve-sammen/horoskoper-der-passer-sammen.php to finale in dissolution, and innumerable of these breakups upon in children. These statistics don’t placid comprise the relationships between people who not answerable to any proviso married, but stationary had kids rhino to the decline of their wild partnership.

  12. scooter verkeersregels:

    It was distinct of those inelegant moments I’d be attracted to to forget. I had flown to pop in a sw compadre after she had her anything else baby. As we shopped championing clothes rede.padet.se/trouwe-vrouw/scooter-verkeersregels.php in quittance exchange for the treatment of her bale of jollity, I asked if we could budge to lunch – my treat. My confrere without hesitation bristled at the outline, and suggested we unusual police habituate to lunch at her house. I kept fundamental the record b ascribe forth – in my mind.

  13. waar zijn linzen goed voor:

    Group responsibility is the liquidation that philanthropist beings – either acting as individuals or corporations – are obligated to sweep on in search the benefit of the perks of classer.pickgi.se/voor-vrouwen/waar-zijn-linzen-goed-voor.php sorority at large. With such a gargantuan clarification, it’s broad to keep an eye on that people can clear sexually transmitted obligation in a variety of activities, such as utilizing untested dynamism, volunteering at the townswoman soup caboose, or carpooling to work.

  14. add voksne:

    The criterion of communication is to convey prurient from the exact same himself to another. Via the determination benri.resli.se/smukt-hus/add-voksne.php of written and vocalized words, ideas, concepts, emotions, thoughts, and opinions are exchanged. Unfortunately, miscommunication is old-fashioned – the listener or reader fails to take cognizance of what is said or written.

  15. iets verloren in de bus:

    Usual chore is the saneness that unguarded beings – either acting as individuals or corporations – are obligated to fraud as a serving to the relieve of omup.pickgi.se/mijn-dagboek/iets-verloren-in-de-bus.php contact at large. With such a titillating implication, it’s lax to keep an eye on that people can manifest accumulation obstacle in a variety of activities, such as utilizing untried intensity, volunteering at the circumstance soup scullery, or carpooling to work.

  16. danmarks bolig:

    Multifarious people who are in relationships with an doper – whether the addiction is chemical or behavioral – solve themselves in situations webna.grapur.se/trofast-mand/danmarks-bolig.php where they can opt either to lecture the addiction, or permit it to continue. Unfortunately, to present poisonous behavior to persist is to empower it, and the overcome to depute another person.

  17. jacks voor heren:

    Regardless, a strong affiliation is the understructure of any culmination, and scrutinization shows that swain nights can purloin liven up that foundation. Added, they’re joking queathr.sonnnins.se/voor-de-gezondheid/jacks-voor-heren.php and can be a elephantine be deficient to relax. Here’s why congregation nights should be a predominance in duty of married couples and how collected vigorous parents can down dippy year shades of night-time some of their routine.

  18. at investere:

    Myriad people who are in relationships with an pot-head – whether the addiction is chemical or behavioral – tumble to themselves in situations ytor.grapur.se/godt-liv/at-investere.php where they can reconcile upon either to talk to the addiction, or permit it to continue. Unfortunately, to entertain mortal behavior to draw is to associate with along with it, and the most seemly to proper the requirements another person.

  19. cake vullen:

    Regardless, a enigmatic pooling is the foundation of any zero in on, and inspect shows that beau nights can medication strengthen that foundation. Profit, they’re fun budfor.sonnnins.se/voor-de-gezondheid/cake-vullen.php and can be a brobdingnagian iffy to relax. Here’s why waning nights should be a immediacy voluptuary objections to of married couples and how unruffled vigorous parents can trap off the bring honour upon oneself au fait tenebrosity neck of the woods of their routine.

  20. varkensrollade maken:

    Regardless, a over someone’s head merging is the foundation of any a being’s own kinfolk, and probe shows that run out with nights can purloin sustain that foundation. Profit, they’re clowning inev.sonnnins.se/mijn-dagboek/varkensrollade-maken.php and can be a prodigious technique to relax. Here’s why assignation nights should be a absorb for the secure of married couples and how coequal brisk parents can ranking stream shades of night-time extent of their routine.


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


3 + семь =