Mobile app version of vmapp.org
Login or Join
Deb1703797

: Use .htaccess to make pretty URLs that expand abbreviation codes Yes, I know, there are tons of questions like this, but I can't find one which solves my problem so at cost of receiving downvotes

@Deb1703797

Posted in: #Htaccess #ModRewrite #Php #Url #UrlRewriting

Yes, I know, there are tons of questions like this, but I can't find one which solves my problem so at cost of receiving downvotes I'm going to ask this again. Even a duplicate link may help me.

This is a job that I've never done before, I have this kind of URL demo.html?code=IT-ROM-FCO where:


IT is the IATA code for "Italy"
ROM is the IATA code for "Rome"
FCO is the IATA code for "Aeroporto di Roma Fiumicino".


I have to rewrite the above URL to display like this airports/italy/rome/aeroporto-di-roma-fiumicino, the strings for the result are coming from an API service.

I know the simple rewrite to change products.php?id=7 to products/7 but I never done such task (get an URL - retrieve some data in PHP w/ the given code - "pretty" print the new URL)

As I really don't know how to achieve this job I have no code example, sorry.

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Deb1703797

1 Comments

Sorted by latest first Latest Oldest Best

 

@Heady270

I'd recommend keeping the codes in the URL. There are some advantages to do so:


Codes are easy to keep static. Names of places often change over time. If the codes are there you don't have to keep records of old names and implement redirects based on old names.
It is easy to rewrite when the data you need for the web-app is in the URL. .htaccess is not great for lookup tables. Putting 25,000 rewrite rules into .htaccess would be a performance killer.


I'd recommend using a URL like: /IT-ROM-FCO/airports/italy/rome/aeroporto-di-roma-fiumicino You would use the following rewrite rule to put the codes into the parameter and remove the slug:

RewriteRule ^/?([A-Z]+-[A-Z]+(-[A-Z]+)?).* /demo.html?code= [L]


That would take any URL that has two or three abbreviations at the beginning and put them into the code parameter. That should support either your code=IT-ROM or code=IT-ROM-FCO cases you mentioned in the comments.

Then when you generate URLs on your site, put the pretty version in the hrefs:

<a href="/IT-ROM-FCO/airports/italy/rome/aeroporto-di-roma-fiumicino">


You'll also need to "canonicalize" your URLs. The URL /IT-ROM-FCO/foo-bar will then show the same content. It is probably easiest to solve this by using a meta link rel canonical tag in the head of the page with the pretty URL. That will tell Google which version is your preferred URL.

<link rel="canonical" href="https://example.com/IT-ROM-FCO/airports/italy/rome/aeroporto-di-roma-fiumicino">

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme