Forwarding : to localhost:80/dir/ (apache)


Hello again StackExchange! First post on Superuser.

I've installed apache and PHP on my computer and it works just fine when i enter "localhost" on my computer. But what i want, is when someone types http://<my ip>:<random port number that isn't used> i want it to redirect to http://localhost/internet/. How do i do this with port forwarding? And what do i need to configure in Apache?

I know this might be question #87465094 on port forwarding, but i haven't seen any solutions for my problem here on Superuser nor the rest of the internet.


Best Answer

First of all, you're mixing two concepts into one idea.

  • TCP/IP Port Forwarding
  • HTTP Redirection

You can achieve what you want by combining the two, but they are separate concepts.

HTTP Redirection

So, let's ignore port forwarding for the time being. Let's set up the redirection part first.

$ sudo editor /etc/apache2/sites-available/thews_site

This creates a new configuration file for a new site configuration in Apache. In it, we can place the whole configuration for our site.

Our VirtualHost

Let's define your new Apache site:

NameVirtualHost *:12345
<VirtualHost *:12345>
        Redirect /

This creates a new site that can be reached on any local IP, but only on port 12345.

The site definition itself is rather short. It only has 1 configuration entry. The redirect to the target site.

Apache Port Configuration

We also need to tell Apache to listen on our new port!

$ sudo echo "Listen 12345" >> /etc/apache2/ports.conf

This will add the line Listen 12345 at the end of /etc/apache2/ports.conf. Alternatively, you could add it yourself using a text editor.

Now let's enable the site

$ sudo a2ensite thews_site
$ sudo invoke-rc.d apache2 restart

This will set our previously defined site to be enabled. The second command will restart Apache.


If you enter http://localhost:12345 into your browser now, you should be redirected to!

Port Forwarding

Now you can set up the port forwarding. You would do that on your router. Tell your router to forward your public port 33333 to your local port 12345.

Now if someone would surf to your-public-ip:33333 they get redirected to

These examples were all for Debian based environments. Hopefully you'll be able to adapt them if you need to.

Good luck :)