Flask Sitemap Example

This is a simple example of how to add a sitemap.xml to your Flask web app.

Step 1: Create the Sitemap Generator Script


from flask import Flask, render_template_string
from flask_sitemap import Sitemap

app = Flask(__name__)
sitemap = Sitemap(app=app)

@sitemapper.include(lastmod="2023-08-13")
@app.route('/')
def index():
    return render_template_string("Hello, this is the homepage!")

@sitemapper.include(lastmod="2023-08-13")
@app.route('/about')
def about():
    return render_template_string("This is the about page.")

if __name__ == '__main__':
    app.run()
    

Step 2: Install Required Packages


pip install Flask-Sitemap
    

Step 3: Configure Sitemap


app.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = True
app.config['SITEMAP_URL_SCHEME'] = 'https'
app.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = True
app.config['SITEMAP_INCLUDE_SUBDOMAINS'] = {'www'}
    

Step 4: Generate Sitemap


@app.route('/sitemap.xml', methods=['GET'])
def sitemap():
    return sitemap.generate()
    

Step 5: Submit Sitemap to Search Engines

Use tools like Google Search Console to submit your sitemap URL.

Step 6: Testing

Run your Flask app and access the /sitemap.xml route in your browser to ensure that the sitemap is being generated correctly.