I had my site under subfolder and I decided to move to the root level of the domain.
The main challenge was to keep all articles on the same path as a subfolder while redirecting the URL to the root of the domain or another location.
Apache
Apache HTTP server supports RewriteCond
. To make this change, edit your .htaccess
or httpd.conf
file and add the below lines to it:
RewriteEngine on
RewriteBase /
RewriteRule ^subfolder/(.*)$ /$1 [R=301,NC,L]
Here we’re using /
as our base and our RewriteRule
works for all URLs in our subfolder by using regular expressions. R=301
specifies a permanent redirect.
Nginx
We can achieve similar redirection with the Nginx web server using the rewrite
directive in your /etc/nginx/nginx.conf
or /etc/nginx/conf.d/default.conf
:
location ^~ /subfolder {
rewrite ^/subfolder(.*)$ $1 last;
}
Here ^~
modifier ensures that this prefix location continues to take precedence if you were to add any regex locations in the future.
IIS
In IIS, we can use the Rewrite module to rewrite URLs that are in a subfolder and we want to appear as if they were in the root. You can edit your web.config
file in your webroot folder (%SystemDrive%\inetpub\wwwroot
) with something like:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Root_URL_Rewrite" stopProcessing="true">
<match url="^(.*)" />
<action type="Rewrite" url="/subfolder/{R:0}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Alternatively, you can additionally use the URL Rewrite UI in IIS Manager to add an inbound rule.
Cloudflare
We can achieve similar redirection using Cloudflare by following below steps:
- Log into your Cloudflare account.
- Click the appropriate Cloudflare account for the domain where you want to add URL forwarding.
- Click the Rules app, then click the Page Rules tab.
- Under Page Rules, click Create Page Rule. The Create Page Rule dialog opens for your domain.
- Now, under If the URL matches, enter the URL pattern for a subfolder that should match the rule, like
https://example.com/subfolder
. - Next, click Add a Setting and choose Forwarding URL from the drop-down menu.
- Click Select Status Code and choose 301 (Permanent Redirect) or 302 (Temporary Redirect).
- Enter the destination URL for your root domain and click Save and Deploy to finish.
The above example is to redirect everything from https://geekflare.com/blog to https://geekflare.com
Wrapping Up
As you can see, redirecting or mapping a subfolder to root or another URL is a common task and is supported by most popular browsers with different options.
Next, find out how you can host multiple websites on a single IP.