[How To] Cleaner URLs
Posted
#4144
(In Topic #832)
Standard member

For anyone who wants less subdirectories in their entry/topic URLs
Hello all, just thought I'd share a quick tip as I realized how extensively I use it on my website. I spoke about this in a video I made, but it will be easier for people to find and copy in text.By default, Composr generates URLs for forum topics and news entries that are fairly long, even when on the "very simple" setting: if I have a forum called "General chat" and someone posts a topic there, the default URL will be https://example.com/forum/topicview/browse/general-chat/topic-name. I wanted cleaner-looking URLs, so here's what I've been doing:
First, we want to make a shorter URL that redirects transparently to the longer one. I use Apache as my web server, so I placed this redirect in my .htaccess file:
Code
RewriteRule ^forum-topic/(.*)$ /forum/topicview/browse/$1
Although we can now type our shorter URL in manually, Composr is still going to send users to the longer URL. In order to change this, I'm modifying the PHP file of each block/page that links to one of these content types.
Whenever one of the PHP files builds one of these URLs, they're going to call a function called build_url. This line of code usually looks something like this:
Code
$url = build_url($map, get_module_zone('topicview'));
Code
$almost_url = build_url($map, get_module_zone('topicview'));
$url = str_replace("/forum/topicview/browse/", "/forum-topic/", $almost_url);
In the end, Composr is still internally using the longer URL to locate the content, but our users see the shorter one in their URL bar while browsing our website, and that's the one they'll share as well.
You have to be careful when you're coming up with your redirects. Because of the nature of what we're doing (with a str_replace), each long string you're replacing needs a unique short string: I wasn't able to use /forums/ for /forum/forumview/browse/ and /forum/topicview/browse/, I had to use /forums/ for one and /forum-topic/ for the other. I'm also using this to rename /news/view/ to /episode/, and /members/view/ to /member/.
I'm sure some of the people reading this know more about programming than I do, so feel free to chime in if you know of other ways to achieve this. I've been using my method for a while, and it's working great for me.
1 guest and 0 members have just viewed this.

