My GitHub
When writing code to handle HTTP redirects, the specific implementation depends on the programming language and framework you use. Here are simple examples of implementing redirection in several different programming languages and frameworks:
Python - Flask
In Python's Flask framework, you can use redirect()
functions for redirection:
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/old_url')
def old_url():
return redirect('/new_url', code=302)
@app.route('/new_url')
def new_url():
return "This is the new URL"
if __name__ == '__main__':
app.run()
Python - Django
In Django you can use HttpResponseRedirect
:
from django.http import HttpResponseRedirect
def old_view(request):
return HttpResponseRedirect('/new_view/')
Node.js - Express
In the Express framework for Node.js:
const express = require('express');
const app = express();
app.get('/old_url', (req, res) => {
res.redirect('/new_url');
});
app.get('/new_url', (req, res) => {
res.send('This is the new URL');
});
app.listen(3000);
PHP
In PHP you can use header()
functions:
<?php
header('Location: /new_url.php');
exit;
?>
Java - Servlet
In Java Servlet:
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "new_url.jsp");
The above are just simple redirect examples. In actual applications, redirection usually involves more logic, such as condition checking, authentication, etc. Depending on your needs, you can also set different types of HTTP status codes for redirection, such as 301 (permanent redirection), 302 (temporary redirection), etc.