-3

I have my own website and I want this like stackoverflow have

When you look at the url there is a nice url like: https://stackoverflow.com/questions/40587870/javascript-variable-in-bootstrap-tooltip

When I only enter https://stackoverflow.com/questions/40587870 it send me to the full url.

This is what I have now: http://www.exmaple.com/projects.php?id=1

How can I make this on my own website?

Community
  • 1
  • 1
Sander Jochems
  • 141
  • 2
  • 13
  • Build a `htaccess` with this rewrite, you can use the search function on SO or your favorite search engine to find more information. – Antony Jan 31 '17 at 15:12
  • Have you tried doing any searches around SO and see if you can piece an .htaccess together? This is a pretty common thing and has been solved a lot. – Jeremy Harris Jan 31 '17 at 15:13
  • Possible duplicate of [Rewrite domain name/url with htaccess](http://stackoverflow.com/questions/33187889/rewrite-domain-name-url-with-htaccess) – Jeremy Harris Jan 31 '17 at 15:13
  • @JeremyHarris could you send me a example how to fix this? – Sander Jochems Jan 31 '17 at 15:14
  • @JeremyHarris that is not what i want, i dont wa sub domain only the /id/name on the back on the URL – Sander Jochems Jan 31 '17 at 15:19
  • You may look into [`RewriteMap`](https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritemap), which allows to map from an id to string. – Olaf Dietsche Jan 31 '17 at 16:06

1 Answers1

1

You need some sort of database for this, which maps an id to its appropriate slug. This could be as simple as a text file containing the mappings, e.g.

41960970 htaccess-url-rewriting-id-and-name
40587870 javascript-variable-in-bootstrap-tooltip

You can then define a RewriteMap

RewriteMap id2slug txt:/path/to/file.txt

and then use it in a rule

RewriteRule ^questions/([^/]+)$ /questions/$1/${id2slug:$1} [R,L]

This rule captures the id from the request and then redirects the client to the same URL with a slug appended.


Instead of a text file, you can also use other forms like dbm, dbd, or even an external program providing the mapping.

Be aware though, that RewriteMap is only available in the main server or virtual host configuration.


When you don't have access to the main config, you might simulate this with a script doing the redirect, e.g.

RewriteRule ^questions/([^/]+)$ /id2slug.php?id=$1 [L]

and in the script, retrieve the slug from a database and send back

$id = $_GET['id'];
$slug = ...;
header('Location: http://www.example.com/questions/' . $id . '/' . $slug);
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198